antdv upload customRequest 前端上传方法

本文介绍如何在Ant Design Vue库中使用upload组件的customRequest选项来自定义前端上传文件的逻辑,涉及到typescript和es6语法的应用,适用于Vue.js前端项目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html:
<a-upload
    v-model:file-list="fileList"
    list-type="picture-card"
    :before-upload="beforeUpload"
    @change="handleChange"
    :show-upload-list="false"
    :customRequest="customImageRequest"
>
    <div class="upload-box" v-if="imageUrl">
        <img :src="imageUrl" alt="avatar" />
        <div class="delete" @click="delteImg">
            <DeleteOutlined />
        </div>
    </div>

    <div v-else>
        <plus-outlined />
        <div class="ant-upload-text">上传签名</div>
    </div>
</a-upload>

js:

// 图片压缩成base64
function getBase64(img: Blob, callback: (base64Url: string) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
}

const fileList = ref([]);
// 上传文件改变时的状态
const handleChange = (info: any) => {
    if (info.file.status === undefined) {
       fileList.value = fileList.value.filter((item, index) => {
            return index < fileList.value.length - 1;
        });
    }

    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};
// 上传文件之前的钩子,参数为上传的文件,若返回 false则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 File或 Blob对象则上传 resolve 传入对象)。注意:IE9 不支持该方法。
const beforeUpload = (file: FileItem) => {
    const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/tiff' ||
        file.type === 'image/jpg';
    if (!isJpgOrPng) {
        message.error('请上传jpeg,png,tiff,jpg格式图片');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
        message.error('上传图片太大,已超出10M');
        return false;
    }

    return true;
};
// 通过覆盖默认的上传行为,可以自定义自己的上传实现(只写了前端没有写请求)
const customImageRequest = (info:any)=>{
    const { file } = info;
    getBase64(file, (base64Url: string) => {
        imageUrl.value = base64Url;
    });
    setTimeout(()=>{
        loading.value = false;
    })
};
// 删除图片
const delteImg = (e:Event)=>{
    e.stopPropagation();
    imageUrl.value = '';
};

### 实现 Ant Design Vue 中多文件上传功能 为了实现在 Ant Design Vue (antdv) 中的多文件上传功能,可以利用 `a-upload` 组件并配置其属性来满足需求。通过设置特定参数可以让组件支持多个文件的同时选择与上传。 #### 配置 a-upload 支持多选文件 在 `<a-upload>` 标签内添加 `multiple="true"` 属性允许用户一次选取多个文件[^1]: ```html <a-upload :multiple="true"> <button type="primary">点击上传</button> </a-upload> ``` 此段代码使得按钮触发时能够打开文件对话框让用户挑选超过一个以上的文档或媒体资源。 #### 自定义上传行为 对于希望控制何时真正发起网络请求的情况,则需自定义上传逻辑而不是依赖于默认的行为。这可以通过监听 change 事件,在适当时候调用 API 完成实际的数据传输工作。 下面是一个完整的例子展示怎样收集所选中的所有文件并在最终确认后再执行批量上传操作[^2]: ```html <template> <div id="app"> <!-- 使用 action="" 来阻止自动提交 --> <a-upload name="file" listType="picture-card" :multiple="true" v-model:fileList="fileList" @preview="handlePreview" @change="handleChange" > <div v-if="fileList.length < 8"> <plus-outlined /> <div style="margin-top: 8px">Upload</div> </div> </a-upload> <a-button type="primary" @click="submitFiles()">Submit All Files</a-button> <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel"> <img alt="example" style="width: 100%" :src="previewImage" /> </a-modal> </div> </template> <script setup lang="ts"> import { ref, defineComponent } from 'vue'; import axios from 'axios'; const fileList = ref([]); let previewVisible = ref(false); let previewImage = ref(''); function handleChange(info) { console.log('changed:', info.file.name); } async function submitFiles() { const formData = new FormData(); fileList.value.forEach(file => { formData.append('files[]', file.originFileObj); }); try { await axios.post('/upload', formData, { headers: {'Content-Type': 'multipart/form-data'} }); alert('All files uploaded successfully!'); } catch(error){ console.error('There was an error uploading the files!',error); } } // ...其他函数省略... </script> ``` 上述示例展示了如何创建一个多文件上传界面,并提供了一个按钮用于触发展示已选择的所有文件到服务器的操作。注意这里假设后端有一个 `/upload` 接口用来接收这些文件流数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值