You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native iOS应用上传JPG至Azure Blob无法打开但含Base64数据问题

问题分析与解决方案

你的核心问题是base64数据处理错误,导致上传到Azure Blob的二进制内容不正确,具体问题点和修复方案如下:

错误点拆解

  1. base64前缀冗余:你在生成base64Data时手动添加了data:image/jpeg;base64,前缀,但reader.result.split(",")[1]已经是纯base64字符串。加上前缀后,Buffer.from(base64Data, "base64")会把前缀也当作base64内容解码,生成错误的二进制数据。
  2. Content-Length错误:你用base64字符串的长度作为请求的Content-Length,但实际上传的是解码后的二进制数据,两者长度完全不匹配,Azure无法正确解析文件。
  3. 多余的Content-Encoding头:既然已经将base64解码为二进制,就不需要再声明Content-Encoding: base64,这个头会让Azure错误地认为上传的内容是base64编码的,进一步导致文件损坏。

修复后的代码(推荐方案:直接处理二进制)

const saveFile = async () => {
  const currentDate = new Date();
  const dateString = currentDate.toUTCString();

  // 直接读取图片二进制数据,跳过base64转换减少出错概率
  const response = await fetch(selectedImage);
  const arrayBuffer = await response.arrayBuffer();
  const fileBuffer = Buffer.from(arrayBuffer);

  var config = {
    method: "put",
    maxBodyLength: Infinity,
    url: "https://clubmanpics.blob.core.windows.net/playerpics/newfile13.jpg",
    headers: {
      "x-ms-version": "2017-11-09",
      "x-ms-date": dateString,
      "x-ms-blob-type": "BlockBlob",
      Authorization: `Bearer ${token}`,
      "Content-Type": "image/jpeg",
      "Content-Length": fileBuffer.length, // 使用二进制数据的实际长度
    },
    data: fileBuffer, // 直接上传二进制数据
  };

  axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });
};

可选方案(保留base64中转的修复)

如果坚持要通过base64处理,只需修正base64的提取逻辑:

const saveFile = async () => {
  const currentDate = new Date();
  const dateString = currentDate.toUTCString();

  const response = await fetch(selectedImage);
  const fileData = await response.blob();
  const base64Data = await new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(fileData);
    // 只保留纯base64字符串,不要添加前缀
    reader.onload = () => resolve(reader.result.split(",")[1]);
    reader.onerror = (error) => reject(error);
  });

  const fileBuffer = Buffer.from(base64Data, "base64");

  var config = {
    method: "put",
    maxBodyLength: Infinity,
    url: "https://clubmanpics.blob.core.windows.net/playerpics/newfile13.jpg",
    headers: {
      "x-ms-version": "2017-11-09",
      "x-ms-date": dateString,
      "x-ms-blob-type": "BlockBlob",
      Authorization: `Bearer ${token}`,
      "Content-Type": "image/jpeg",
      "Content-Length": fileBuffer.length,
    },
    data: fileBuffer,
  };

  axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });
};

内容的提问来源于stack exchange,提问作者Stuart Ridout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:13:28