axios - 文件上传、下载进度
axios onDownloadProgress
| axios({ |
| url: 'https://www.***.com/***.png', |
| method: 'get', |
| onDownloadProgress (progress) { |
| console.log(Math.round(progress.loaded / progress.total * 100) + '%'); |
| } |
| }) |
axios onUploadProgress
| axios({ |
| url: URL, |
| method: 'post', |
| data: { |
| ...params |
| }, |
| onUploadProgress (progress) { |
| console.log(Math.round(progress.loaded / progress.total * 100) + '%'); |
| } |
| }) |
XMLHttpRequest
XMLHttpRequest.upload
ElementUi upload
| export default function upload(option) { |
| if (typeof XMLHttpRequest === 'undefined') { |
| return; |
| } |
| |
| const xhr = new XMLHttpRequest(); |
| const action = option.action; |
| |
| if (xhr.upload) { |
| xhr.upload.onprogress = function progress(e) { |
| if (e.total > 0) { |
| e.percent = e.loaded / e.total * 100; |
| } |
| option.onProgress(e); |
| }; |
| } |
| |
| const formData = new FormData(); |
| |
| if (option.data) { |
| Object.keys(option.data).forEach(key => { |
| formData.append(key, option.data[key]); |
| }); |
| } |
| |
| formData.append(option.filename, option.file, option.file.name); |
| |
| xhr.onerror = function error(e) { |
| option.onError(e); |
| }; |
| |
| xhr.onload = function onload() { |
| if (xhr.status < 200 || xhr.status >= 300) { |
| return option.onError(getError(action, option, xhr)); |
| } |
| |
| option.onSuccess(getBody(xhr)); |
| }; |
| |
| xhr.open('post', action, true); |
| |
| if (option.withCredentials && 'withCredentials' in xhr) { |
| xhr.withCredentials = true; |
| } |
| |
| const headers = option.headers || {}; |
| |
| for (let item in headers) { |
| if (headers.hasOwnProperty(item) && headers[item] !== null) { |
| xhr.setRequestHeader(item, headers[item]); |
| } |
| } |
| xhr.send(formData); |
| return xhr; |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步