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

React Native集成RapidAPI AI Picture Colorizer上传图片报500错误求助

问题排查与修复方案

你的代码存在4处关键错误,修改后即可正常请求:

  • FormData的image字段传值错误:仅传入文件名无法让后端获取到真实文件内容,React Native环境下上传本地文件需要传入包含本地文件uri、文件名、文件类型的结构化对象
  • axios请求的data字段错误:你填写的是字符串'[form]',应该直接传入构造完成的FormData实例
  • 多余的请求头配置:不需要手动指定multipart/form-data的boundary值,axios发送FormData时会自动生成匹配的请求头,手动指定反而会导致请求格式校验失败
  • 冗余参数:API已不支持base64传参,可以关闭image picker的includeBase64配置减少内存占用

修改后的代码

1. 修改selectGallaryImage方法,存储需要的文件完整信息

selectGallaryImage() {
    const options = {
      includeBase64: false, // 关闭不需要的base64生成
    };
    launchImageLibrary(options, response => {
      if (response.didCancel) {
        console.log('User canceled Image');
      } else if (response.error) {
        console.log('Image picker error');
      } else if (response.customButton) {
        console.log('User pressed custom Button');
      } else {
        const asset = response.assets[0];
        this.setState(
          {
            // 存储上传需要的三个参数
            fileUri: asset.uri,
            fileName: asset.fileName,
            fileType: asset.type,
          },
          () => console.log('文件信息获取完成'),
        );
        this.goForAxios();
      }
    });
  }

2. 修改goForAxios方法,修正请求配置

goForAxios() {
    const { fileUri, fileName, fileType } = this.state;
    const form = new FormData();
    // 传入符合React Native要求的文件对象
    form.append('image', {
      uri: fileUri,
      name: fileName,
      type: fileType
    });
    form.append('renderFactor', '10');

    this.setState({menu: false});
    console.log('Starting request');
    axios
      .request({
        method: 'POST',
        url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
        headers: {
          // 删掉手动写的content-type,axios会自动生成
          'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
          'x-rapidapi-key': '[替换为你自己的API-KEY]',
        },
        data: form, // 直接传入FormData实例,不要加引号和括号
      })
      .then(response => {
        this.setState({
          loading: false,
          dataSource: response.data,
        });
      })
      .catch(error => {
        console.error(error);
      });
  }

额外注意事项

如果是iOS设备出现请求失败,可以尝试把fileUri开头的ph://替换为file://后再传入FormData。

内容的提问来源于stack exchange,提问作者Jacob Sherwood

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:15:02