Ant-design-vue 图片上传

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中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值