Ant Design Vue和VUE3下的upload组件使用以及文件预览
<template>
<a-upload
:file-list="fileList"
:remove="handleRemove"
:before-upload="beforeUpload"
@change="handleChange"
>
<a-button>
<upload-outlined></upload-outlined> Click to Upload
</a-button>
</a-upload>
<img v-if="previewImage" :src="previewImage" style="width: 100%; max-width: 600px" />
</template>
<script>
import { UploadOutlined } from '@ant-design/icons-vue';
import { message, upload } from 'ant-design-vue';
export default {
components: {
UploadOutlined,
},
data() {
return {
fileList: [],
previewImage: null,
};
},
methods: {
handleRemove(file) {
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
},
beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
},
handleChange(info) {
if (info.file.status === 'uploading') {
this.fileList = [...info.fileList];
return;
}
if (info.file.status === 'done') {
// Get response from server
getBase64(info.file.originFileObj, imageUrl => {
this.previewImage = imageUrl;
this.fileList = [...info.fileList];
});
}
},
},
};
function getBase64(file, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(file);
}
</script>
这段代码展示了如何在Ant Design Vue中使用Upload组件以及如何处理文件的上传和预览。它包括了文件类型和大小的校验,以及文件的上传和预览处理。在实际应用中,你可以根据自己的需求对这段代码进行相应的调整。
评论已关闭