antd upload上传如何获取文件宽高

2023-02-12 15:06:40

目录antdupload上传获取文件宽高antd上传文件限制大小reactHooks总结antdupload上传获取文件宽高项目新加的需求,需要判断上传图片的宽高,查了一下antd-uploa...

目录
antd upload上传获取文件宽高
antd上传文件限制大小 react Hooks
总结

antd upload上传获取文件宽高

项目新加的需求,需要判断上传图片的宽高,查了一下antd-upload组件貌似不支持这个查询,因此需要使用外部的API

直接上代码:beforeUpload 方www.cppcns.com

handleBeforeUpload = async (file, fileList) => {
    const {fileMinSize = 0,fileMinWH,fileMaxWH, fileMaxSize = 50,uploadFormat = '',uploadFormatError = ''} = this.component.props;
    const isInRange = ((file.size > (fileMinSize * 1024 * 1024)) && (file.size < (fileMaxSize * 1024 * 1024)));
    let isTrueType = true,isFileWH = true;//类型,尺寸
    return new Promise((resolve, reject) =>{
      //校验格式
      if(uploadFormat != ''){
        let acceptArr = uploadFormat.split(',');
        let fileType = file.name.substring(file.name.lastIndexOf('.'));
        if(!acceptArr.includes(fileType)){
          isTrueType = false;
          this.message.error((uploadFormatError == '') ? '请上传规则范围内的文件!' : uploadFormatError);
          this.base.ss({'data.fileList': fileList.pop()});
        }
      }
      //校验大小

      if (!isInRange) {//大小的标识
        this.message.error((fileMaxSize == 50) ? '请上传规则范围内的文件!' : '文件最大不能超过'+ fileMaxSize + 'M!');
        this.base.ss({'data.fileList': fileList.pop()});
      }


      //校验宽高
      /*********************************/

      if(fileMinWH && fileMaxWH){//做下过滤有的图片需要过滤
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          //加载图片获取图片真实宽度和高度
          var image = new Image();
          image.src=reader.result;
          image.onload = () =>{
            var width = image.width;//图片的宽
            var height = image.height;//图片的高
            if(width < fileMinWH || width > fileMaxWH || height < fileMinWH || height > fileMaxWH){
              isFileWH = false;
              this.message.error('***宽高需要均大于600像素,小于4000像素');
              this.base.ss({'data.fileList': []});
              reject();
            }else{
              resolve(isFileWH && isInRange && isTrueType)
            }
          };
        };
        /**********************************/
      }else{
        resolve(isInRange && isTrueType);
      }
    })
  };

这样这个功能就可以完美的解决了,*包着的代码是最主要的。

antd上传文件限制大小 react Hooks

 const uploadImages = {
        action: requestUrl + '/api/common/CommonUpload',
        headers: {
            SessionKey: `${localStorage.getItem('sk')}`,
        },
        data: (file) => {
            return {
                UploadType: 1027,//后端定义的type
                Id: uuidv4(),
                FileType: getUploadFileType(file),
            };
        },
        beforeUpload: (file) => {// 礼品image
            const limitFileNameLen = 100;
            return new Promise((resolve, reject) => {
                if (file.name && file.name.length > limitFileNameLen) {
                    message.error('Please upload a file with a file name less than 100 characters');
                    //请上传文件名不超过100个字符的文件
                    return Promise.reject();
                }
                const limitM = 2;
                const isLimit = file.size / 1024 / 1024 <= limitM;
                console.log(isLimit);
                if (!isLimit) {
                    message.error('The size exceeds the limit');
                    return Promise.reject();
                }
                return resolve();
            });
        },
    }

模板:

<Upload
        {...uploadImages}
        accept=".jpeg,.png,.jpg"
        listType="picture-card"
        fileList={fileList}
        onChange={handleChange}
        onPreview={handlePreview}
      >
        {fileList.length >= 4 ? null : uploadButton}
      </Upload>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。