工作有那么个需求,从官网 issue中获悉:
使用 Upload 的 customRequest 用 FileReader 读取。
customRequest
从官网获悉其参数:
onProgress: (event: { percent: number }): void
onError: (event: Error, body?: Object): void
onSuccess: (body: Object): void
data: Object
filename: String
file: File
withCredentials: Boolean
action: String
headers: Object
具体代码:
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Upload, message, Button, Icon } from "antd";
/**
获取file,通过FileReader获取图片的 base64
*/
function customRequest(option) {
const formData = new FormData();
formData.append("files[]", option.file);
const reader = new FileReader();
reader.readAsDataURL(option.file);
reader.onloadend = function(e) {
console.log(e.target.result);// 打印图片的base64
if (e && e.target && e.target.result) {
option.onSuccess();
}
};
}
/***
上传验证格式及大小
*/
function beforeUpload(file) {
const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
if (!isJpgOrPng) {
message.error("只能上传JPG或PNG文件!");
return false;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error("图片大小需小于2MB!");
return false;
}
return isJpgOrPng && isLt2M;
}
const props = {
customRequest: customRequest,
showUploadList: false, // 不展示文件列表
beforeUpload: beforeUpload
};
ReactDOM.render(
<Upload {...props}>
<Button>
<Icon type="upload" /> Click to Upload
</Button>
</Upload>,
document.getElementById("container")
);
codesandbox 示例:https://codesandbox.io/s/great-silence-lzdwm?file=/index.js
可在log中查看结果