首页 > 解决方案 > Flutter how to send multiple files to http post

问题描述

I'd like to send two files to http post

curl looks like this

curl -X POST "https://api-us.faceplusplus.com/facepp/v3/compare" \
-F "api_key=<api_key>" \
-F "api_secret=<api_secret>" \
-F "image_file1 =file1" \
-F "image_file1 =file2"

I tried like this.

   File first;
   File second;
      var uri = Uri.parse('https://api-us.faceplusplus.com/facepp/v3/compare');
      var request = new http.MultipartRequest("POST", uri);
       request.fields['api_key'] = apiKey;
       request.fields['api_secret'] = apiSecret;
       request.files.add(await http.MultipartFile.fromPath('image_file1', first.path, contentType: new MediaType('application', 'x-tar')));
       request.files.add(await http.MultipartFile.fromPath('image_file2', second.path, contentType: new MediaType('application', 'x-tar')));
       var response = await request.send();
       print(response);

But it returns this

NoSuchMethodError: Class 'String' has no instance getter 'path'.

How can I send these properly?

标签: dartflutter

解决方案


它看起来不像firstsecond实际上是Files。当它们肯定是文件时,如下例所示,我得到 401(正如预期的那样,因为我有一个虚拟 api 密钥)。

main() async {
  File first = File('pubspec.yaml');
  File second = File('analysis_options.yaml');
  Uri uri = Uri.parse('https://api-us.faceplusplus.com/facepp/v3/compare');
  http.MultipartRequest request = new http.MultipartRequest('POST', uri);
  request.fields['api_key'] = 'apiKey';
  request.fields['api_secret'] = 'apiSecret';
  request.files.add(await http.MultipartFile.fromPath('image_file1', first.path,
      contentType: new MediaType('application', 'x-tar')));
  request.files.add(await http.MultipartFile.fromPath(
      'image_file2', second.path,
      contentType: new MediaType('application', 'x-tar')));
  http.StreamedResponse response = await request.send();
  print(response.statusCode);
}

推荐阅读