Ad

Flutter How To Send Multiple Files To Http Post

- 1 answer

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?

Ad

Answer

It doesn't look like first and second are actually Files. When they are definitely files, as in the following example, I get 401 (as expected, as I have a dummy api key).

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);
}
Ad
source: stackoverflow.com
Ad