antd vue Ant Design Vue Upload图片上传组件 beforeUpload不能阻止上传行为

解决antd vue upload组件 beforeUpload不能阻止上传的行为

Ant Design Vue网站给出的描述

网页地址:Upload
在这里插入图片描述

这里描述说可以直接返回false 阻止文件上传,但其实并不能阻止,经过一番尝试后
请注意查看我的示例:

const beforeUpload = async (file: UploadFile<unknown>): Promise<boolean> => {
  // 坑:必须要返回一个 Promise,promise 中 必须返回false 才能阻止上传,通过校验必须返回true和 resolve 否则会阻止上传
  return new Promise((resolve) => {
    const { supportFileType, maxSize, aspectUnit } = props;
    const { size = 0, name = "" } = file || {};

    if (!isFormatValidate(name, supportFileType)) {
      message.error("请上传支持的文件格式!");
      return false;
    }

    const isSizeValidate: boolean = size <= maxSize; // 文件大小判断
    if (!isSizeValidate) {
      const msg = `文件最大不超过${getSizeByByte(maxSize, aspectUnit)}`;
      message.error(msg);
      console.log("msg", msg);
      return false;
    }
    fileList.value = [...fileList.value, file];
    resolve(true);
    return true;
  });
};
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Antd Vue 提供了一个 Upload 组件,可以用于上传图片。 使用方法如下: 1. 安装 antd-vue 和 axios: ``` npm install antd-vue axios --save ``` 2. 引入 antd-vue 和 axios: ```js import Vue from 'vue' import Antd from 'ant-design-vue' import 'ant-design-vue/dist/antd.css' import axios from 'axios' Vue.use(Antd) Vue.prototype.$axios = axios ``` 3. 在组件中使用 Upload 组件: ```html <template> <div> <a-upload :action="uploadUrl" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError" :show-upload-list="false" > <a-button> <a-icon type="upload"></a-icon> Click to Upload </a-button> </a-upload> </div> </template> <script> export default { data() { return { uploadUrl: '/api/upload', } }, methods: { beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' if (!isJpgOrPng) { this.$message.error('You can only upload JPG/PNG file!') } const isLt2M = file.size / 1024 / 1024 < 2 if (!isLt2M) { this.$message.error('Image must smaller than 2MB!') } return isJpgOrPng && isLt2M }, onSuccess(response) { this.$message.success('Upload success') console.log(response) }, onError(error) { this.$message.error('Upload failed') console.log(error) }, }, } </script> ``` 上面的代码中,Upload 组件的 action 属性指定了上传图片的 URL,before-upload 属性用于校验上传的文件类型和大小,on-success 和 on-error 属性分别用于处理上传成功和上传失败的情况。 在 beforeUpload 方法中,我们校验了上传的文件类型和大小,如果不符合要求,则会弹出错误提示。 在 onSuccess 方法中,我们打印了上传成功后返回的数据,可以根据实际需求进行处理。 在 onError 方法中,我们打印了上传失败的错误信息,可以根据实际需求进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值