Flutter Dio动态添加MultipartFile对象到Map



我有自定义数据

File avatar = File('path/to/file');
Map<String, dynamic> data = {
  'name': 'John',
  'avatar': avatar
}

我如何将我的数据作为FormData对象发送到服务器?

我尝试通过循环我的数据创建MultipartFile类的对象,但在我的情况下发送文件路径作为文件的字符串实例。下面是我的代码:

data.forEach((key, value) {
  if (value is File) {
    String fileName = value.path.split('/').last;
    data.update(key, (value) async {
      return await MultipartFile.fromFile(value.path, filename: fileName);
    });
  }
});
FormData formData = FormData.fromMap(data);
var response = await dio.post("/send", data: formData);

但是使用Dio我可以像这样上传文件:

FormData formData = FormData.fromMap({
    "name": "wendux",
    "age": 25,
    "file": await MultipartFile.fromFile(file.path,filename: fileName)
});

为什么我不能动态添加MultipartFile到我的Map ?

您没有等待您的数据

await Future.wait(data.map((k, v){
if(v is File){
v = await MultipartFile.fromFile(value.path, filename: fileName);
}
  return MapEntry(k, v);
}));

请查看在forEach循环中填充列表之前我的异步调用正在返回

可以不带音频发送。在这里,我编写了整个代码,包括库和响应。请测试下面的代码,因为在我的情况下dio不工作,你的情况非常类似于我的情况。

Just send it with simple http request

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';
   Map<String, String> headers = {
      'Content-Type': 'multipart/form-data',        
    };
    Map jsonMap = {
      "name": "wendux",
      "age": 25,          
    };
 String imagePath, // add the image path in varible 
 var request = http.MultipartRequest('POST', Uri.parse(url));
    request.headers.addAll(headers);
    request.files.add(
      http.MultipartFile.fromBytes(
        'orderStatusUpdate',
        utf8.encode(json.encode(jsonMap)),
        contentType: MediaType(
          'application',
          'json',
          {'charset': 'utf-8'},
        ),
      ),
    );
    if (imagePath != null) {
      final mimeTypeData = lookupMimeType(imagePath).split('/');
      final file = await http.MultipartFile.fromPath('images', imagePath,
          contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
      print((mimeTypeData[0].toString())); // tells picture or not
      print((mimeTypeData[1].toString())); // return extention
      request.files.add(file);
    }
    http.StreamedResponse streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);
    print(response.statusCode);
    print(response.body);

相关内容

  • 没有找到相关文章

最新更新