ant design vue2 上传文件
时间: 2023-09-09 09:13:15 浏览: 106
Ant Design Vue2 提供了一个上传组件 `Upload`,可以用来上传文件。
使用方法如下:
1. 引入组件
```vue
<template>
<div>
<a-upload
:action="uploadUrl"
:headers="uploadHeaders"
:data="uploadData"
:multiple="false"
:show-upload-list="false"
:before-upload="beforeUpload"
:custom-request="customRequest"
>
<a-button icon="upload">上传文件</a-button>
</a-upload>
</div>
</template>
<script>
import { Upload, Button } from 'ant-design-vue';
export default {
name: 'UploadDemo',
components: {
'a-upload': Upload,
'a-button': Button,
},
data() {
return {
uploadUrl: '/api/upload',
uploadHeaders: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
uploadData: {
user: 'test',
},
};
},
methods: {
beforeUpload(file) {
console.log('before upload', file);
return true;
},
customRequest(option) {
console.log('custom request', option);
const formData = new FormData();
formData.append('file', option.file);
option.onSuccess({}, option.file);
},
},
};
</script>
```
2. 配置组件属性
- `action`: 上传接口地址
- `headers`: 上传请求头
- `data`: 上传请求参数
- `multiple`: 是否支持多文件上传,默认为 `true`
- `show-upload-list`: 是否显示上传列表,默认为 `true`
- `before-upload`: 上传之前的钩子函数,返回 `false` 可以取消上传
- `custom-request`: 自定义上传函数,可以通过此函数实现自定义上传方式,比如使用 `axios` 发送上传请求
3. 处理上传结果
上传成功后,会触发 `onSuccess` 事件,可以在此事件里面处理上传结果。
```vue
<template>
<div>
<a-upload
:action="uploadUrl"
:headers="uploadHeaders"
:data="uploadData"
:multiple="false"
:show-upload-list="false"
:before-upload="beforeUpload"
:custom-request="customRequest"
@on-success="onUploadSuccess"
>
<a-button icon="upload">上传文件</a-button>
</a-upload>
</div>
</template>
<script>
import { Upload, Button } from 'ant-design-vue';
export default {
name: 'UploadDemo',
components: {
'a-upload': Upload,
'a-button': Button,
},
data() {
return {
uploadUrl: '/api/upload',
uploadHeaders: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
uploadData: {
user: 'test',
},
};
},
methods: {
beforeUpload(file) {
console.log('before upload', file);
return true;
},
customRequest(option) {
console.log('custom request', option);
const formData = new FormData();
formData.append('file', option.file);
option.onSuccess({}, option.file);
},
onUploadSuccess(response, file) {
console.log('upload success', response, file);
},
},
};
</script>
```
注意:上传成功后的响应结果可能是一个 JSON 字符串,需要使用 `JSON.parse()` 方法将其转换为 JavaScript 对象。
阅读全文