Flutter - 如何在表单数据中发送多个图像

Flutter - How to send multiple images in formdata

我想使用 dio 和 formData 在 flutter 中上传多张图片。我所做的是创建一个用于将 MultipartFile 存储在数组中的 for 循环,然后将数组传递给“img[]”的数据。但是,如果我传递了数组,我无法上传图片,但如果我上传单张图片,它就可以正常工作。

这是我的代码。

 var arr = new List(3);
 
 for (var i=0; i <_tryPath.length; i++) {
    arr[i] = await MultipartFile.fromFile(imageFile[i].path, filename: 
    imageFile[i].path.split('/').last, contentType: new MediaType('image','jpg'));
 };

 print('this is arr = $arr');

 FormData formData = new FormData.fromMap({
    "name": "Max",
    "location": "Paris",
    "age": 21,
    "img[]": arr,
 });

 // dio is in another class here in AuthService.
 AuthService().donateRegister(formData).then((val) async {
    print('successful');
    print(val.data);
 });

你能帮我在 formData 中上传很多图片吗?我也不想限制 MediaType。如果我还要上传 pdf/docu 或 jpg MediaType 怎么办?我会很感激你的时间和回答。谢谢!

您可以使用 for 循环来设置图像列表,如下所示

这里我用的是multi_image_picker

 Future<int> addMultiImage({MyData myData, List<Asset> files}) async {
    var formData = FormData.fromMap({
     "name": "Max",
    "location": "Paris",
    "age": 21,
    });
    for (int i = 0; i < files.length; i++) {
      var path = await FlutterAbsolutePath.getAbsolutePath(files[i].identifier);
      formData.files.addAll([
        MapEntry("img", await MultipartFile.fromFile(path, filename: path))
      ]);
    }

    Response response = await dioHelper.post(
      "myPaths",
      queryParameters: {
       
      },
      data: formData,
    );

您可以使用 mime 包获取 mime 类型。

import 'package:path/path.dart' as path;
import 'package:mime/mime.dart';

String getFileName(String _path){
    return path.basename(_path) 
}

FilePickerResult? result = await FilePicker.platform.pickFiles(
  allowMultiple: true,
  type: FileType.custom,
  allowedExtensions: ['jpg', 'pdf', 'doc'],
);

if(result != null) {
   List<MultipartFile> files = result.paths.map((path) => 
     MultipartFile.fromFileSync(
        path, 
        filename: getFileName(path),
        contentType: MediaType(
            lookupMimeType(getFileName(path)).split('/')[0],
            lookupMimeType(getFileName(path)).split('/')[1],
        ),
   )
).toList();  
   var dio = Dio();
   var formData = FormData.fromMap({
    'name': 'wendux', // other parameter may you need to send
    'age': 25, // other parameter may you need to send
    'files': files,
  });

  var response = await dio.post('url', data: formData); 
  // check response status code
  if(response.statusCode == 200){
     // it's uploaded
  }

} else {
   // User canceled the picker
}