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

Flutter调用Infura IPFS /api/v0/add接口返回400错误求助

问题排查与解决方案

你遇到的400错误核心原因是:IPFS /api/v0/add 接口不支持JSON格式的请求体,它要求通过multipart/form-data格式上传文件的二进制内容,而非仅传递文件路径字符串。你的代码用json.encode(body)提交JSON数据,完全不符合接口要求,这就是Postman能正常工作但Flutter代码报错的原因。

修正后的代码示例

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<void> uploadToInfuraIPFS(String username, String password, String filePath) async {
  // 构建Basic Auth头
  String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';

  // 初始化multipart请求
  var url = Uri.https('ipfs.infura.io:5001', '/api/v0/add');
  var request = http.MultipartRequest('POST', url);
  
  // 添加认证头
  request.headers['Authorization'] = basicAuth;
  
  // 添加文件到请求体(注意:这里要传文件的二进制内容,不是路径)
  try {
    File file = File(filePath);
    if (await file.exists()) {
      request.files.add(await http.MultipartFile.fromPath('file', filePath));
    } else {
      print('文件不存在:$filePath');
      return;
    }
  } catch (e) {
    print('读取文件失败:$e');
    return;
  }

  // 发送请求并处理响应
  var response = await request.send();
  var responseBody = await response.stream.bytesToString();
  
  print('响应状态码:${response.statusCode}');
  print('响应内容:$responseBody');
}

关键注意事项

  • 必须使用MultipartRequest构建请求,不能用普通的http.post加JSON体
  • 接口要求的file参数是文件的二进制内容,不是文件路径字符串
  • 确保你的Flutter应用已获取对应的文件访问权限(Android需在AndroidManifest.xml中添加READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE;iOS需在Info.plist中添加NSDocumentFolderUsageDescription等权限描述)
  • 确认username和password是Infura IPFS项目的API密钥对(不是你的Infura账号密码)

内容的提问来源于stack exchange,提问作者Giacomo Galletti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:05:19