vue3 antdesign vue 文件上传
时间: 2023-10-10 15:15:38 浏览: 126
Ant Design Vue 提供了一个 Upload 组件,可以用于文件上传。具体使用方法如下:
1. 安装 Ant Design Vue
```
npm install ant-design-vue --save
```
2. 引入 Upload 组件
在需要使用 Upload 组件的页面中引入:
```javascript
import { Upload } from 'ant-design-vue';
```
3. 使用 Upload 组件
在模板中使用 Upload 组件:
```html
<template>
<div>
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:before-upload="beforeUpload"
:on-success="onSuccess"
:on-error="onError"
:defaultFileList="defaultFileList"
>
<a-button icon="upload">Click to Upload</a-button>
</a-upload>
</div>
</template>
```
其中,action 属性指定文件上传的地址,before-upload 属性可以对文件进行预处理,on-success 和 on-error 属性分别在上传成功和上传失败时调用,defaultFileList 属性用于设置默认的文件列表。
4. 完整代码
```html
<template>
<div>
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:before-upload="beforeUpload"
:on-success="onSuccess"
:on-error="onError"
:defaultFileList="defaultFileList"
>
<a-button icon="upload">Click to Upload</a-button>
</a-upload>
</div>
</template>
<script>
import { Upload, message } from 'ant-design-vue';
export default {
components: {
'a-upload': Upload,
'a-message': message,
},
data() {
return {
defaultFileList: [
{
uid: '1',
name: 'xxx.png',
status: 'done',
url: 'http://www.baidu.com/xxx.png',
},
{
uid: '2',
name: 'yyy.png',
status: 'done',
url: 'http://www.baidu.com/yyy.png',
},
],
};
},
methods: {
beforeUpload(file) {
console.log('beforeUpload', file);
const isJPG = file.type === 'image/jpeg';
if (!isJPG) {
this.$message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('Image must smaller than 2MB!');
}
return isJPG && isLt2M;
},
onSuccess(response, file, fileList) {
console.log('onSuccess', response, file, fileList);
this.$message.success('Upload successfully');
},
onError(error, file, fileList) {
console.log('onError', error, file, fileList);
this.$message.error('Upload failed');
},
},
};
</script>
```
以上就是使用 Ant Design Vue 的 Upload 组件实现文件上传的步骤。
阅读全文