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

React Native中如何使用Axios以二进制形式上传图片?

React Native中用Axios上传二进制图片到服务器

问题分析

你当前代码传递的是base64字符串,但服务器需要原始二进制图片数据(对应Postman里的--data '@文件路径',即直接把文件内容作为请求体发送),同时Axios配置结构有误,导致请求头和参数未正确生效。

解决方案

1. 修正Axios配置结构

Axios的请求配置无需嵌套在config属性中,所有配置项(headers、maxBodyLength等)均为顶级属性,同时要补上Postman里的Authorization头。

2. 将本地图片转为二进制数据

React Native没有浏览器的File API,可通过两种方式获取二进制数据:

方式一:使用react-native-fs读取文件

先安装依赖:

npm install react-native-fs --save

编写读取并转换的函数:

import RNFS from 'react-native-fs';

// 将本地图片URI转为Uint8Array(二进制数据)
const getBinaryImageData = async (imageUri) => {
  // 移除file://前缀
  const filePath = imageUri.replace('file://', '');
  // 读取文件为base64格式
  const base64Str = await RNFS.readFile(filePath, 'base64');
  // 将base64转为Uint8Array
  const binaryStr = atob(base64Str);
  const uint8Array = new Uint8Array(binaryStr.length);
  for (let i = 0; i < binaryStr.length; i++) {
    uint8Array[i] = binaryStr.charCodeAt(i);
  }
  return uint8Array;
};

方式二:用Fetch API读取Blob转ArrayBuffer(无需额外依赖)

// 将本地图片URI转为ArrayBuffer(二进制数据)
const getBinaryImageData = async (imageUri) => {
  const response = await fetch(imageUri);
  const blob = await response.blob();
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsArrayBuffer(blob);
  });
};

3. 最终请求代码

try {
  // 获取二进制图片数据
  const binaryImage = await getBinaryImageData(imageData[0].uri);
  
  // 发送请求
  const res = await request({
    url: 'device/image',
    method: 'PATCH',
    data: binaryImage,
    headers: {
      'Content-Type': 'image/jpeg',
      'accept': 'application/json',
      'Authorization': 'Basic MTIwODU4MTM3MTk6Z2tNUWpRVWM='
    },
    maxBodyLength: Infinity,
    maxContentLength: Infinity,
    responseType: 'json'
  });

  console.log('res ::: ', res.data);
} catch (e) {
  console.error('Oops :: ', e);
  toast.show({
    type: 'error',
    message: e.message || 'Something went wrong',
    position: 'top'
  });
}

关键说明

  • 禁止传递base64字符串作为请求体,必须转为二进制格式(Uint8Array或ArrayBuffer),否则服务器无法识别为图片文件。
  • 确保Content-Type设置为image/jpeg,与Postman保持一致。
  • 硬编码Authorization头存在安全风险,建议从环境变量或安全存储中读取。

内容的提问来源于stack exchange,提问作者Aditya Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:57:36