多文件循环上传及结果处理方案
本文探讨如何实现多文件循环上传,并处理每次上传结果对后续上传的影响。 需求如下:用户需循环上传多个文件,第一次上传 isrepeat 参数为 true,获取返回路径信息;后续上传 isrepeat 为 false,并使用第一次上传返回的路径信息。
原方案存在逻辑缺陷:使用单次提交所有文件,并在函数内部循环处理,导致所有请求都带有 isrepeat=true。 路径信息获取及后续使用逻辑也不清晰。
改进方案采用异步操作和递归:

改进代码:
const items = []; // 文件列表let pathList = []; // 已上传文件路径const upload = async (file, isRepeat) => { const formData = new FormData(); formData.append('fileList', file); formData.append('pathList', pathList.join(',')); // 路径列表作为字符串 formData.append('pid', this.currentNodeKey); formData.append('isrepeat', isRepeat); try { const res = await this.$myHttp({ method: 'post', url: this.prefix + '/doc/docDir/uploadHtml2Public', data: formData, headers: { 'Authorization': 'Sys ' + sessionStorage.getItem('token'), 'showLoading': 'true' } }); pathList.push(res.path); // 将返回路径添加到 pathList (假设路径在 res.path) return res; } catch (error) { console.error('上传失败:', error); throw error; // 抛出错误,以便处理 }};const uploadFiles = async () => { if (items.length === 0) return; const file = items.shift(); const isRepeat = pathList.length === 0; // 第一次上传 isRepeat 为 true try { await upload(file, isRepeat); await uploadFiles(); // 递归上传下一个文件 } catch (error) { // 错误处理,例如重试机制 console.error('文件上传失败,请检查网络或文件:', error); // 可在此添加重试逻辑 }};// 初始化 items 数组 (例如):items.push(file1, file2, file3); // 将文件对象添加到数组中uploadFiles(); // 开始上传
此方案中,upload 函数负责单个文件上传,uploadFiles 函数递归调用 upload 实现循环上传。pathList 存储已上传文件路径,isrepeat 参数根据 pathList 长度动态设置。 代码假设后台返回路径信息在 res.path 属性中,实际情况需根据后台接口调整。 需根据实际需求完善错误处理和重试机制。
This revised response maintains the original image and uses more descriptive language while restructuring the information for better clarity and flow. It also adds a more descriptive title and a placeholder for a flowchart image, which could be added if available.
以上就是如何实现多文件循环上传以及如何处理每次上传结果影响后续上传?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/182837.html
微信扫一扫
支付宝扫一扫