如何解决文件上传时服务器无响应导致客户端无限等待的问题
解决方案
核心实现逻辑
通过给上传请求增加超时检测机制解决服务器无响应的问题:
- 为上传请求设置合理的超时阈值(可根据业务允许的最大上传时长调整,常规场景建议设为30~60秒),超过阈值未收到服务端响应将自动中断请求,抛出异常
- 在异常捕获分支中识别超时错误,即可终止加载动画,向用户展示对应错误提示
代码修改示例
你当前使用的API.post一般是Axios等常见请求库的封装,这类库默认都支持超时配置,修改后的代码如下:
export const upload = async (file) => { let result = null; try { const formData = new FormData(); formData.append("file", file, file.name); result = await API.post( "/fileupload", formData, // 新增超时配置,单位为毫秒,以下示例为30秒超时 { timeout: 30000 } ); if (result.status === 200) { return result.data; } else { return "Upload file failed."; } } catch (ex) { console.log("parsing failed", ex); // 识别超时错误(Axios超时错误的code为ECONNABORTED,其他请求库可对应调整判断逻辑) if (ex.code === 'ECONNABORTED') { return "服务器响应超时,请稍后重试"; } return "上传失败,请检查网络后重试"; } };
无内置超时的兼容方案
如果你使用的请求库不支持内置超时配置,可以自行封装一个通用超时包裹函数:
// 通用超时封装函数 const withTimeout = (promise, timeoutMs) => { return new Promise((resolve, reject) => { const timer = setTimeout(() => { const err = new Error('请求超时'); err.code = 'ECONNABORTED'; reject(err); }, timeoutMs); promise .then(resolve) .catch(reject) .finally(() => clearTimeout(timer)); }) } // 上传方法改造 export const upload = async (file) => { let result = null; try { const formData = new FormData(); formData.append("file", file, file.name); // 用withTimeout包裹原请求,设置30秒超时 result = await withTimeout(API.post("/fileupload", formData, {}), 30000); if (result.status === 200) { return result.data; } else { return "Upload file failed."; } } catch (ex) { console.log("parsing failed", ex); if (ex.code === 'ECONNABORTED') { return "服务器响应超时,请稍后重试"; } return "上传失败,请检查网络后重试"; } };
上层调用提示
你在业务代码中调用upload方法时,只要拿到返回的错误信息,就可以终止加载动画,向用户弹出对应的错误提示即可。
内容的提问来源于stack exchange,提问作者Sirisha N
相关产品推荐
相关产品推荐

