Flutter如何将多个文件发送到http发布

时间:2018-09-25 15:15:11

标签: dart flutter

我想将两个文件发送到http post

卷曲看起来像这样

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"

我尝试过这样。

   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);

但是它返回了

  

NoSuchMethodError:类'String'没有实例获取方法'path'。

如何正确发送这些邮件?

2 个答案:

答案 0 :(得分:1)

看起来firstsecond实际上不是File。当它们绝对是文件时,如下面的示例所示,我得到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);
}

答案 1 :(得分: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;
    }
  }
}