Ant Design of Vue中对a-upload组件封装,1.实现上传功能2.实现下载功能3.单个文件上传不能超过1024m4.显示上传的文件列表5.文件列表右侧有删除按钮,可以实现删除功能6.用ts语法实现前面功能
时间: 2024-02-01 13:15:09 浏览: 26
以下是对a-upload组件的封装,实现了上传、下载、文件列表展示、删除等功能,并使用了TypeScript语法:
```typescript
<template>
<div>
<a-upload
:action="uploadUrl"
:before-upload="beforeUpload"
:on-success="onUploadSuccess"
:on-error="onUploadError"
:on-remove="onRemove"
>
<a-button icon="upload">上传文件</a-button>
</a-upload>
<a-table :columns="columns" :data-source="fileList" row-key="uid"></a-table>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Upload, Button, Table, Icon, Modal, message } from 'ant-design-vue';
import { AxiosResponse } from 'axios';
interface FileItem {
uid: string;
name: string;
status: 'uploading' | 'done' | 'error' | 'removed';
url?: string;
}
@Component({
components: {
'a-upload': Upload,
'a-button': Button,
'a-table': Table,
'a-icon': Icon,
'a-modal': Modal,
},
})
export default class MyUpload extends Vue {
private fileList: FileItem[] = [];
private uploadUrl = '/api/upload';
private columns = [
{
title: '文件名',
dataIndex: 'name',
},
{
title: '状态',
dataIndex: 'status',
},
{
title: '操作',
scopedSlots: { customRender: 'operation' },
},
];
private beforeUpload(file: File) {
const isLt1G = file.size / 1024 / 1024 < 1024;
if (!isLt1G) {
message.error('不能上传超过1G的文件!');
}
return isLt1G;
}
private onUploadSuccess(response: AxiosResponse, file: FileItem) {
file.status = 'done';
file.url = response.data.url;
message.success('上传成功!');
}
private onUploadError(error: Error, file: FileItem) {
file.status = 'error';
message.error('上传失败!');
}
private onRemove(file: FileItem) {
Modal.confirm({
title: '确定删除该文件吗?',
onOk: () => {
const index = this.fileList.findIndex((item) => item.uid === file.uid);
this.fileList.splice(index, 1);
message.success('删除成功!');
},
onCancel: () => {},
});
}
private downloadFile(url: string) {
const a = document.createElement('a');
a.href = url;
a.target = '_blank';
a.download = url.split('/').pop() || '';
a.click();
}
private getOperationSlot(record: FileItem) {
if (record.status === 'done' && record.url) {
return (
<div>
<a-button type="link" onClick={() => this.downloadFile(record.url || '')}>
下载
</a-button>
<a-button type="link" onClick={() => this.onRemove(record)}>
删除
</a-button>
</div>
);
}
if (record.status === 'uploading') {
return <a-icon type="loading" />;
}
return null;
}
}
</script>
```
在这个组件中,我们使用了Ant Design of Vue提供的Upload、Button、Table、Icon、Modal和Message等组件,实现了上传、下载、文件列表展示、删除等功能。其中,beforeUpload方法用于限制上传文件大小,onUploadSuccess和onUploadError方法用于处理上传成功和失败的情况,onRemove方法用于删除文件,downloadFile方法用于下载文件,getOperationSlot方法用于自定义操作列的内容。