ant design中upload组件 上传图片压缩

2021-12-07 13:51:58 浏览数 (2)

不想描述多余的,直接看代码简单直接

const [defaultFileList, setDefaultFileList] = useState([]);

代码语言:javascript复制
 <Upload
                accept="image/*"
                customRequest={uploadImage}
                onChange={handleOnChange}
                listType="picture-card"
                showUploadList={true}
                fileList={defaultFileList}
                onRemove={removeFileItem}
                beforeUpload={beforeUpload}
                className="image-upload-grid"
              >
                {defaultFileList.length >= 3 ? null : uploadButton}
              </Upload>
  • customRequest 自定义上传图片的
代码语言:javascript复制
  const uploadImage = async options => {
    const { onSuccess, onError, file, onProgress, fileList } = options;
    const fmData = new FormData();
    fmData.append('file', file);
    try {
      fetch(`***/api/common/upload_file`, {
        method: 'POST',
        credentials: 'include',
        body: fmData
      })
        .then(response => response.json())
        .catch(error => {
          message.error('error');
        })
        .then(response => {
          onSuccess('Ok');
          if (response.code === 0) {
            let list = {
              uid: file.uid,
              data: response.data
            };
            //setDefaultFileList 这个这个一定需要
            setDefaultFileList([
              ...defaultFileList,
              { ...file, url: `https:www.***.com/api/file/download/${response.data}`, uid: response.data }
            ]);
            setState({
              imgList: [...imgList, list]
            });
            setState({
              imgfileId: [...imgfileId, response.data]
            });
          } else {
            message.error(response.msg);
          }

          console.log('Success:', response);
        });
    } catch (err) {
      console.log('Eroor: ', err);
      const error = new Error('Some error');
      onError({ err });
    }
  };
  • beforeUpload 压缩图片在这一步操作
代码语言:javascript复制
const beforeUpload = (file, fileList) => {
    return new Promise(resolve => {
      // 图片压缩
      let reader = new FileReader(),
        img = new Image();
      reader.readAsDataURL(file);
      reader.onload = function(e) {
        img.src = e.target.result;
      };

      img.onload = function() {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');

        let originWidth = this.width;
        let originHeight = this.height;

        canvas.width = originWidth;
        canvas.height = originHeight;

        context.clearRect(0, 0, originWidth, originHeight);
        context.drawImage(img, 0, 0, originWidth, originHeight);

        canvas.toBlob(
          blob => {
            let imgFile = new File([blob], file.name, { type: file.type }); // 将blob对象转化为图片文件
            resolve(imgFile);
          },
          file.type,
          0.2
        ); // file压缩的图片类型
      };
    });
  };
  • onChange 一定需要
代码语言:javascript复制
  const handleOnChange = ({ file, fileList, event }) => {
    let a = {
      uid: '1',
      name: file.name,
      status: 'uploading',
      url: ''
    };
    setDefaultFileList([a]);
  };
  • onRemove 也需要
代码语言:javascript复制
  const removeFileItem = (file, fileList) => {
    console.log('file', file, fileList);
    console.log(defaultFileList);

    const matchKey = file.uid !== undefined ? 'uid' : 'name';
    const removed = defaultFileList.filter(item => item.uid !== file[matchKey]);
    if (removed.length === defaultFileList.length) {
      return null;
    }
    setDefaultFileList(removed);
    return removed;
  };

0 人点赞