vue3+element-plus调用接口 实现文件上传
时间: 2023-11-12 18:05:11 浏览: 225
好的,关于这个问题,你需要先在你的项目中安装 element-plus 和 axios 这两个库,然后按照以下步骤来实现文件上传:
1. 在组件中导入要使用的库:
```
import { defineComponent } from 'vue'
import { ElUpload } from 'element-plus'
import axios from 'axios'
```
2. 创建上传函数,并将 formData 发送至服务器:
```
export default defineComponent({
components: { ElUpload },
methods: {
uploadFile(file) {
const formData = new FormData()
formData.append('file', file.raw)
axios.post('/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
.then(response => {
console.log(response.data);
})
}
}
})
```
3. 在模板中引入上传组件:
```
<template>
<el-upload
class="upload-demo"
:action="uploadFile"
list-type="picture"
:on-success="onSuccess"
:on-change="onChange"
:before-upload="beforeUpload"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</template>
```
4. 最后,通过 on-success 回调函数来处理服务器返回的上传成功信息:
```
export default defineComponent({
components: { ElUpload },
methods: {
uploadFile(file) {
const formData = new FormData()
formData.append('file', file.raw)
axios.post('/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
.then(response => {
console.log(response.data);
})
},
onSuccess(response, file, fileList) {
console.log('上传成功');
console.log(response);
console.log(file);
console.log(fileList);
}
}
})
```
希望这个回答能够帮到你!
阅读全文