背景
平时工作中经常会遇到需要上传文件的情况,如果你用ant design 或者element ,它们都提供了上传的组件。 我们分别来看一下element 和 antd 手动上传怎么处理:
ant design 手动上传文件
antd官网有手动上传的demo:
在这里简单写一写实现,主要有 在jsx中引入Upload组件,将 fileList 作为props传入,fileList为选择的文件列表,和 上传函数的实现。
// jsx
// Upload 为上传组件
Select File
上传文件
// handleUpload 的实现 使用 fetch 请求
const handleUpload = () {
const formData = new FormData();
fileList.forEach((file) => { // fileList 是要上传的文件数组
formData.append('files[]', file);
});
fetch(url: 'http:just.a.url.demo', {
method: 'POST',
headers: {
credentials: 'same-origin'
// 'Content-Type': 'multipart/form-data' // 不要加上这个文件类型说明
},
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Element 手动上传文件
element 和antd 不同,通过上传组件拿回的数据,element又封装了一层,所以传数据稍有不同。
以下是简单实现:
// template
:file-list="fileList"
:auto-upload="false">
选择文件
上传文件
// 上传实现