RNFetchBlob上传Blob图片:Android正常iOS偶发无法解析响应求助
解决RNFetchBlob iOS端上传图片偶尔失败及“cannot parse response”错误
可能原因及修复方案
1. 移除手动设置的Content-Type头
RNFetchBlob处理multipart/form-data请求时,会自动生成并添加带boundary参数的Content-Type头。手动设置"Content-Type": "multipart/form-data"会覆盖自动生成的规范头,导致服务器无法正确解析表单数据,iOS端对这类不规范请求的兼容性更差。
修改后的请求头:
{ Authorization: "Basic ZGF2aXM6c2U3ZW5zZTdlbg==", // 移除手动设置的Content-Type otherHeader: "foo", }
2. 先验证响应内容再解析JSON
“cannot parse response”通常是因为服务器返回非有效JSON(比如空响应、HTML错误页、非JSON文本)。在调用response.json()前先检查响应内容:
.then((response) => { const responseText = response.text(); console.log("Server response:", responseText); try { return JSON.parse(responseText); } catch (parseErr) { console.error("Failed to parse response:", parseErr); // 按需处理解析失败场景,比如返回默认值或抛出错误 return null; } })
3. 确保iOS文件路径正确且可访问
iOS文件路径格式与Android不同,上传前先检查文件是否存在,避免因路径错误或权限问题导致异常:
// 上传前校验文件存在性 const fileExists = await RNFetchBlob.fs.exists(imgpath); if (!fileExists) { console.error("File not found:", imgpath); return Promise.reject(new Error("File not found")); }
4. 修正上传进度计算的变量冲突
代码中total = written / total;存在变量名重复,会覆盖原始总大小值,导致进度计算错误。修正为:
.uploadProgress({ interval: 5 }, (written, total) => { const progress = written / total; console.log("uploaded", progress); })
完整修正后的代码
return await RNFetchBlob.fs.exists(imgpath).then(async (fileExists) => { if (!fileExists) { console.error("File not found:", imgpath); throw new Error("File not found"); } return RNFetchBlob.fetch( "POST", `${urlToUpload}`, { Authorization: "Basic ZGF2aXM6c2U3ZW5zZTdlbg==", otherHeader: "foo", }, [ { name: "filedata", filename: `image.png`, type: "image/png", data: RNFetchBlob.wrap(imgpath), }, ] ) .uploadProgress({ interval: 5 }, (written, total) => { const progress = written / total; console.log("uploaded", progress); }) .then((response) => { const responseText = response.text(); console.log("Server response:", responseText); try { return JSON.parse(responseText); } catch (parseErr) { console.error("Failed to parse response:", parseErr); return null; } }) .then((d) => { console.log("dddd", d); return d?.url; }) .catch((err) => { console.log("Error in adding a comment", err, err.message); }); });
内容的提问来源于stack exchange,提问作者Rvind Jitta
相关产品推荐
相关产品推荐

