本文探讨如何实现多文件循环上传,并处理每次上传结果对后续上传的影响。 需求如下:用户需循环上传多个文件,第一次上传 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.
以上就是如何实现多文件循环上传以及如何处理每次上传结果影响后续上传?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号