el-upload使用自定义上传方式进行多张图片一次性上传,并获取后端返回值,写出详细代码
时间: 2024-05-07 15:18:57 浏览: 88
以下是使用自定义上传方式进行多张图片一次性上传,并获取后端返回值的代码:
HTML:
```html
<el-upload
class="upload-demo"
action=""
:on-change="handleChange"
:http-request="customUpload"
:show-file-list="false"
:multiple="true"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
```
JavaScript:
```js
methods: {
handleChange(fileList) {
console.log(fileList);
},
customUpload(file) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
xhr.open('POST', '/api/upload');
xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.send(formData);
});
}
}
```
在 `el-upload` 组件中,我们设置 `:http-request` 属性为自定义的上传函数 `customUpload`。在 `customUpload` 函数中,我们使用 `XMLHttpRequest` 发起一个 POST 请求,并将文件添加到 `FormData` 中。最后返回一个 Promise,如果上传成功则调用 `resolve` 并传递后端返回的数据,否则调用 `reject` 并传递错误信息。
在 `handleChange` 方法中,我们可以通过 `fileList` 参数获取到上传成功的文件列表。如果需要获取每个文件的后端返回值,可以在 `customUpload` 函数中将上传的文件名、路径等信息一并返回,然后在 `handleChange` 方法中处理即可。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)