el-upload 自定义发请求
时间: 2023-12-09 22:36:05 浏览: 117
为了自定义el-upload的上传行为,可以使用el-upload的`http-request`属性来自定义上传的实现。下面是一个示例代码,展示如何使用`http-request`属性来自定义上传行为:
```html
<template>
<el-upload
class="upload-demo"
ref="upload"
:action="uploadUrl"
:http-request="uploadFile"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="fileList"
:auto-upload="false"
:show-file-list="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: [],
uploadUrl: 'your-upload-url'
};
},
methods: {
uploadFile(file) {
// 自定义上传行为
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
xhr.upload.addEventListener('progress', event => {
if (event.lengthComputable) {
const percent = Math.floor(event.loaded / event.total * 100);
console.log(`上传进度:${percent}%`);
}
});
xhr.addEventListener('load', () => {
const response = JSON.parse(xhr.responseText);
resolve(response);
});
xhr.addEventListener('error', () => {
const error = JSON.parse(xhr.responseText);
reject(error);
});
xhr.open('POST', this.uploadUrl);
xhr.send(formData);
});
},
handleSuccess(response, file, fileList) {
console.log(response);
},
handleError(error, file, fileList) {
console.log(error); },
submitUpload() {
this.$refs.upload.submit();
}
}
};
</script>
```
在上面的代码中,我们使用`http-request`属性来指定自定义上传行为的实现函数`uploadFile`。在`uploadFile`函数中,我们使用`XMLHttpRequest`对象来发送POST请求,并监听`progress`事件来获取上传进度。在请求完成后,我们使用`resolve`和`reject`函数来返回上传结果或错误信息。
阅读全文