当前位置:   article > 正文

Antd Upload组件自定义上传customRequest,不使用action_antd upload customrequest

antd upload customrequest

业务需求

用户上传图片,不需要先提交到后端或者云存储,在最后点击确定的时候再提交保存图片。

Upload

<Upload
	accept=".jpg , .png"	//文件类型
	maxCount={1}
	showUploadList={false}
	beforeUpload={beforeUpload}	//上传前的钩子
	onChange={handleChange}	//上传中、完成、失败都会调用这个函数
	customRequest={customRequest}	//覆盖默认的上传行为,自定义上传实现
>
	<IonButton fill="clear">上传</IonButton>
</Upload>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

自定义上传

    const customRequest = (option: any) => {
        // const reader = new FileReader();
        // reader.readAsDataURL(option.file); //转为base64格式
        const urlData = URL.createObjectURL(option.file); //转为blob格式(二进制文件)
        console.log("blob:",urlData);
        option.onSuccess();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上传前钩子

    const beforeUpload = (file: any) => {
        console.debug("file type:", file.type);
        const allowFormat = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!allowFormat) {
            present('只允许 JPG/PNG 文件!', 1000)
        }
        const fileSize = file.size / 1024 / 1024 < 5;
        if (!fileSize) {
            present('图片应当小于5MB!', 1000)
        }
        return allowFormat && fileSize;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

状态改变调用

    const handleChange = (info: any) => {
        console.debug("info:", info)
        if (info.file.status === 'done') {
            message.success('上传成功');
        }
        if (info.file.status === 'error') {
            message.error('上传失败');
        }
    };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号