2

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?

Daibaku
  • 11,416
  • 22
  • 71
  • 108

3 Answers3

5

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);
}
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
1
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';

class Post {
  String title = '';
  String description = '';
  List<File> files = [];

  Future<http.StreamedResponse> sendFiles() async {
    try {
      var uri = Uri.parse('https://example.com/api-endpoint');
      var request = http.MultipartRequest('POST', uri);

      // Headers
      request.headers.addAll({
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      });

      // Fields
      request.fields['title'] = title;
      request.fields['description'] = description;

      // Files
      await Future.forEach(
        files,
        (file) async => {
          request.files.add(
            http.MultipartFile(
              'files',
              (http.ByteStream(file.openRead())).cast(),
              await file.length(),
              filename: basename(file.path),
            ),
          )
        },
      );

      return await request.send();
    } catch (err) {
      print(err);

      return null;
    }
  }
}
ShomaEA
  • 61
  • 1
  • 4
  • 2
    Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Ran Marciano Mar 25 '21 at 11:09
0

You can try with Flutter DIO Package https://pub.dev/packages/dio

import 'package:dio/dio.dart';

// Create a Dio instance
final Dio dio = Dio();

// Set up the request options
Options options = Options(
  method: 'POST',
);

// Create a FormData instance to hold the files you want to upload
FormData formData = FormData();

// Add the files to the FormData instance
formData.files.addAll([
  MapEntry('file1', await MultipartFile.fromFile(file1Path)),
  MapEntry('file2', await MultipartFile.fromFile(file2Path)),
  // Add more files here if you want
]);

try {
  // Send the POST request
  Response response = await dio.post(
    url,
    data: formData,
    options: options,
  );

  // Do something with the response
  print(response.data);
} catch (e) {
  // show my error
  log(e);
}
Mashood .H
  • 926
  • 6
  • 16