fileReader 的load事件是异步的 通过promise使其同步加载
export const loadFileAsync = (file: File): Promise<string | ArrayBuffer> =>
new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = (e) => {
resolve(e.target?.result ? e.target.result : "");
};
fileReader.onerror = (e) => {
reject(e);
};
});
<input
type="file"
accept="image/*"
onChange={async (e) => {
if (e.target.files && e.target.files.length) {
if (e.target.files[0].size > 1024 * 1024) {
changeImage({ ...params, url: URL.createObjectURL(e.target.files[0]), objectFit: "fill" });
} else {
const res = await loadFileAsync(e.target.files[0]);
res && changeImage({ ...params, url: res as string, objectFit: "fill" });
}
}
}}
/>
不转换base64
URL.createObjectURL(e.target.files[0])
|