如何将 base64 字符串图像转换为 blob 图像以通过表单发送到后端
像这样的一些解决方案对我不起作用
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
我最终找到了一个解决方案,像这样进行一些清洁
export default async function base64ToBlob(dataUrl: string): Promise<Blob> {
let newImage = new Image();
return new Promise((resolve, reject) => {
newImage.onload = () => {
const canvas = document.createElement("canvas");
canvas.width = newImage.width;
canvas.height = newImage.height;
const ctx = canvas.getContext("2d");
ctx?.drawImage(newImage, 0, 0);
canvas.toBlob(
(blob: Blob | null) => {
if (blob) resolve(blob);
else reject;
},
"image/jpeg",
1
);
};
newImage.onerror = reject;
newImage.src = dataUrl;
});
}
并像这样使用
const blob = await base64ToBlob(myBase64);
const form = new FormData();
form.append("image", blob);
const { data } = await HTTPService.post("someurl/image", form);