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

React Native上传文件至Azure时表单数据混入文件问题排查

React Native (Expo + TypeScript) 上传文件至Azure Blob 去除FormData冗余信息方案

问题根源

Azure Blob Storage 的PUT上传接口要求请求体为纯文件二进制数据,而非multipart/form-data格式的FormData封装内容。你之前用FormData上传时,会自动添加boundary分隔符、content-disposition等表单元数据,这些内容会被写入Blob文件首尾,导致文件损坏;而Postman/Angular直接传File对象时,请求体是纯二进制,因此能正常工作。React Native中直接传File对象为空,是因为RN的File对象与Web环境不一致,需通过Expo的文件系统工具读取Uri对应的原始内容。

解决方案:直接上传二进制数据

通过Expo FileSystem读取文件Uri的原始内容,转换为Blob/ArrayBuffer后直接PUT到Azure,避免FormData的封装。

步骤1:安装依赖(若未安装)

确保已安装expo-file-system:

npx expo install expo-file-system

步骤2:Axios上传示例

import axios from 'axios';
import * as FileSystem from 'expo-file-system';

/**
 * 上传文件至Azure Blob
 * @param fileUri 本地文件Uri(如Expo ImagePicker返回的uri)
 * @param azureBlobUrl 带权限的Azure Blob上传URL(如含SAS Token的URL)
 * @param contentType 文件MIME类型(如image/jpeg、image/png)
 */
async function uploadToAzure(fileUri: string, azureBlobUrl: string, contentType: string) {
  // 读取文件为Base64编码
  const base64Data = await FileSystem.readAsStringAsync(fileUri, {
    encoding: FileSystem.EncodingType.Base64,
  });

  // 将Base64转换为Blob
  const blob = await fetch(`data:${contentType};base64,${base64Data}`).then(res => res.blob());

  try {
    await axios.put(azureBlobUrl, blob, {
      headers: {
        'Content-Type': contentType,
        // 若Azure需要授权,添加对应头(如Authorization: Bearer <token> 或SAS Token参数)
      },
    });
    console.log('文件上传成功');
  } catch (error) {
    console.error('上传失败:', error);
  }
}

步骤3:Fetch上传示例

import * as FileSystem from 'expo-file-system';

async function uploadToAzureWithFetch(fileUri: string, azureBlobUrl: string, contentType: string) {
  const base64Data = await FileSystem.readAsStringAsync(fileUri, {
    encoding: FileSystem.EncodingType.Base64,
  });
  const blob = await fetch(`data:${contentType};base64,${base64Data}`).then(res => res.blob());

  const response = await fetch(azureBlobUrl, {
    method: 'PUT',
    headers: {
      'Content-Type': contentType,
      // 授权头(按需添加)
    },
    body: blob,
  });

  if (response.ok) {
    console.log('文件上传成功');
  } else {
    console.error('上传失败:', await response.text());
  }
}

关键注意事项

  • ContentType必须匹配:确保传入的contentType与文件实际类型一致,否则Azure可能无法正确识别文件格式。
  • Azure URL权限:上传URL需具备写入权限,建议使用带有效期的SAS Token,避免暴露账户密钥。
  • 大文件处理:若上传大文件,建议改用Azure的块上传(Block Blob)API,避免内存溢出。

内容的提问来源于stack exchange,提问作者Emerson Pwi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:09:24