JS上传图片至Backblaze B2提示文件格式不支持但base64解码正常
问题原因
- 代码中提取的
imagedata是图片的Base64编码文本字符串,直接将该字符串作为请求体上传后,Backblaze B2存储的文件内容是Base64文本而非原始二进制图片数据,因此Windows文件管理器无法直接识别为合法图片格式,只有专门的Base64解码器可以读取文本内容还原出图片。
修复方案
优先选择直接传递原始File对象作为请求体,无需做Base64转码,性能更高且不会出现编码转换错误,修改后代码如下:
const submitForm = () => { const proxyurl = "https://cors-anywhere.herokuapp.com/"; fetch(proxyurl + '你的B2上传接口地址', { method: 'POST', headers: { "Accept": "*/*", "X-Bz-File-Name": file.name, "X-Bz-Content-Sha1": "do_not_verify", "Authorization": "你的授权凭证", "Content-Type": "b2/x-auto", }, // 直接传入原始file对象,fetch会自动处理为二进制流上传 body: file, }) .then((response) => response.json()) .then(res => console.log(res)) .catch((err) => { return { status: 'fail', message: 'API CALL ERROR', error: err.message }; }); };
如果业务逻辑确实需要走Base64转码流程,需要先将Base64字符串转换为二进制Uint8Array再作为请求体上传,新增转换方法并修改请求体参数即可:
// Base64转二进制数组方法 const base64ToUint8Array = (base64) => { const binaryStr = atob(base64); const byteLength = binaryStr.length; const bytes = new Uint8Array(byteLength); for (let i = 0; i < byteLength; i++) { bytes[i] = binaryStr.charCodeAt(i); } return bytes; } const submitForm = () => { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { let imagedata = reader.result.slice(reader.result.indexOf(',') + 1) const proxyurl = "https://cors-anywhere.herokuapp.com/"; fetch(proxyurl + '你的B2上传接口地址', { method: 'POST', headers: { "Accept": "*/*", "X-Bz-File-Name": file.name, "X-Bz-Content-Sha1": "do_not_verify", "Authorization": "你的授权凭证", "Content-Type": "b2/x-auto", }, // 传入转换后的二进制数组 body: base64ToUint8Array(imagedata), }) .then((response) => response.json()) .then(res => console.log(res)) .catch((err) => { return { status: 'fail', message: 'API CALL ERROR', error: err.message }; }); }; reader.onerror = function(e) { console.log('Error : ' + e.type); }; }
内容的提问来源于stack exchange,提问作者Singh
相关产品推荐
相关产品推荐

