Flutter IPFS infura API获取请求仅接收哈希值,而非txt文件的完整内容

whhtz7ly  于 2022-12-19  发布在  Flutter
关注(0)|答案(1)|浏览(174)

作为前一个问题的参考,我正在尝试获取一个txt文件上传到ipfs上,请求如下:

Future<int> downloadItemIPFS(String hash,String localFolder) async {
  String username = FlutterConfig.get('INFURA_PROJECT_ID');
  String password = FlutterConfig.get('INFURA_API_SECRET');
  String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
  String tmpPath = await temporaryDirectoryPath;
  Directory('$tmpPath/$localFolder/').create();
  var list = List<int>.generate(100, (i) => i)..shuffle();
  List<int> names = list.take(5).toList();
  String name = '';
  for (int i = 0; i<names.length; i++) {
    name += names[i].toString();
  }
  //var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash,'output': '$tmpPath/$localFolder/'});
  //http.Response response = await http.post(url, headers: {'Content-Type': "text/plain",HttpHeaders.authorizationHeader: basicAuth},);

  var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash ,'output': '$tmpPath/$localFolder/'});
  var request = http.MultipartRequest("POST", url);
  request.headers['Authorization'] = basicAuth;
  StreamedResponse response = await request.send();
  var result = await http.Response.fromStream(response);
  File file = await File("$tmpPath/$localFolder/$name.txt").writeAsString(result.body);
  print("Body content: ${ await file.readAsString()}");
  return response.statusCode;
}

Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = Directory("$tmpPath/$folder/");
  final List<FileSystemEntity> out = await dir.list().toList();
  return out;
}

我从主体的响应中只接收到文件的哈希值
我尝试在postman上提出同样的要求,收到以下回应:
screenshot 1
screenshot 2

xoefb8l8

xoefb8l81#

代码如下:

var headers = {
  "Authorization": "$basicAuth",
};

var response = await http.Client().get(url, headers: headers);

response.bodyBytes // has your data

使用FileSaver plugin时:

var headers = {
  "Authorization": "$basicAuth",
};

var response = await http.Client().get(url, headers: headers);

if (response.statusCode ~/ 100 == 2) {
  var fileName = response.headers["filename"] ?? "file.txt";

  /* with file_saver plugin */

  await FileSaver.instance.saveFile(
      fileName.split(".").first, response.bodyBytes, "txt",
      mimeType: MimeType.TEXT);

  return;
} else {
  throw Exception("Code ${response.statusCode} - ${response.body}");
}

相关问题