axios上传文件封装
解决方案
在现代Web开发中,文件上传是一项常见的需求。axios
是一个流行的HTTP客户端库,支持浏览器和Node.js环境。为了简化文件上传操作并提高代码的可维护性,我们可以对axios
进行封装,创建一个专门用于处理文件上传的工具函数。介绍如何使用axios
实现文件上传,并提供多种封装思路。
1. 基础封装
最直接的方法是创建一个简单的封装函数,接受文件对象和其他必要的参数(如上传URL、请求头等),然后返回一个Promise。
javascript
import axios from 'axios';</p>
<p>function uploadFile(file, url, config = {}) {
const formData = new FormData();
formData.append('file', file);</p>
<p>return axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data',
...config.headers,
},
...config,
});
}</p>
<p>// 使用示例
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', async (event) => {
try {
const response = await uploadFile(event.target.files[0], '/upload');
console.log('Upload successful:', response.data);
} catch (error) {
console.error('Upload failed:', error);
}
});
2. 增加进度回调
有时候我们需要知道文件上传的进度,可以通过onUploadProgress
选项来实现。
javascript
function uploadFileWithProgress(file, url, onProgress, config = {}) {
const formData = new FormData();
formData.append('file', file);</p>
<p>return axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data',
...config.headers,
},
onUploadProgress: (progressEvent) => {
if (progressEvent.lengthComputable) {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
onProgress(percentCompleted);
}
},
...config,
});
}</p>
<p>// 使用示例
uploadFileWithProgress(
event.target.files[0],
'/upload',
(percent) => {
console.log(<code>Upload progress: ${percent}%
);
},
{ headers: { Authorization: 'Bearer your-token' } }
);
3. 处理多文件上传
如果需要同时上传多个文件,可以在FormData
中添加多个文件项。
javascript function uploadMultipleFiles(files, url, config = {}) { const formData = new FormData();</p> <p>files.forEach((file, index) => { formData.append(<code>files[${index}]
, file); });return axios.post(url, formData, { headers: { 'Content-Type': 'multipart/form-data', ...config.headers, }, ...config, }); }
// 使用示例 const multipleFilesInput = document.querySelector('input[type="file"][multiple]'); multipleFilesInput.addEventListener('change', async (event) => { try { const response = await uploadMultipleFiles(event.target.files, '/upload/multiple'); console.log('Multiple files uploaded successfully:', response.data); } catch (error) { console.error('Upload failed:', error); } });
4. 创建通用上传类
对于更复杂的场景,可以考虑创建一个通用的上传类,以便更好地组织代码和管理状态。
javascript
class FileUploader {
constructor(baseURL, defaultConfig = {}) {
this.baseURL = baseURL;
this.defaultConfig = defaultConfig;
}</p>
<p>uploadSingle(file, endpoint, config = {}) {
const formData = new FormData();
formData.append('file', file);</p>
<pre><code>return axios.post(`${this.baseURL}/${endpoint}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
...this.defaultConfig.headers,
...config.headers,
},
...this.defaultConfig,
...config,
});
}
uploadMultiple(files, endpoint, config = {}) {
const formData = new FormData();
Array.from(files).forEach((file, index) => {
formData.append(`files[${index}]`, file);
});
return axios.post(`${this.baseURL}/${endpoint}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
...this.defaultConfig.headers,
...config.headers,
},
...this.defaultConfig,
...config,
});
}
}
// 使用示例
const uploader = new FileUploader('/api', { headers: { Authorization: 'Bearer your-token' } });
uploader.uploadSingle(event.target.files[0], 'single').then((response) => {
console.log('Single file uploaded successfully:', response.data);
});
uploader.uploadMultiple(event.target.files, 'multiple').then((response) => {
console.log('Multiple files uploaded successfully:', response.data);
});
通过以上几种方式,我们可以根据实际需求选择合适的封装方法,使文件上传操作更加简洁、灵活且易于维护。