Ant-design-vue实现图片上传的前端代码
模版中的代码
<template>
<div class="bg-gray-100 rounded-b-lg p-4 h-48 ">
<div class="flex flex-wrap gap-3 py-1 px-2">
<div v-for="item in fileList" :key="item" class="relative">
<CloseOutlined
class="cursor-pointer bg-gray-300 rounded-full hover:opacity-80 absolute -top-1.5 -right-1.5 z-50"
style="color: ghostwhite; font-size: 13px; padding: 1px;" @click="handleRemove(item)" />
<a-image :src="item.url" style="width: 78px;height: 78px;" class="object-cover rounded-lg" />
</div>
</div>
</div>
<a-upload :multiple="true" :file-list="fileList" :before-upload="beforeUpload" :showUploadList=false>
<a-button>上传图片</a-button>
</a-upload>
</template>
上传逻辑
<script setup>
import { ref, computed } from 'vue';
import { CloseOutlined } from '@ant-design/icons-vue';
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
const fileList = ref([
{
uid: '-1',
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-2',
name: 'yyy.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
]);
const handleRemove = file => {
console.log('删除:',file)
const index = fileList.value.indexOf(file);
const newFileList = fileList.value.slice();
newFileList.splice(index, 1);
fileList.value = newFileList;
};
const beforeUpload = async (file)=> {
console.log('上传之前:',file)
const isImg = (file.type === 'image/jpeg' || file.type === 'image/png');
if (!isImg) {
message.error('请上传图片');
}
await getBase64(file).then(imageUrl => {
file.url = imageUrl;
file.thumbUrl = imageUrl;
});
fileList.value = [...fileList.value, file];
console.log('------------',fileList.value)
return false;
};
const handleUpload = () => {
const formData = new FormData();
fileList.value.forEach(file => {
formData.append('files[]', file);
});
uploading.value = true;
// 调用ajax请求 。。。
};
</script >
点击上传图片会现在div中