使用Multipart和Dio在Flutter上发送多张图像时出现问题

时间:2020-03-26 11:36:43

标签: flutter dart multipartform-data dio

我试图将Flutter上来自Multi Image Picker插件的多个文件发送到我的服务器,为此,我试图使用Dio进行发送。但是Multipart标记也不会上传文件。如何进行?

    Future<Response> _uploadFile() async {

    var catUpload = jsonEncode(incluirCategoriasParaUpload());
    final FormData formData = FormData.fromMap({
      "action": 'add_Anuncio',
      "filial_id": "1",
      "titulo": tituloControler.text,
      "descricao": descricaoControler.text,
      "categorias": catUpload
    });

    for (var val in listaImagensParaUpload) {
      ByteData byteData = await val.getByteData();
      Uint8List pngBytes = byteData.buffer.asUint8List();
      formData.files.add(
          MapEntry("arquivos",
              await MultipartFile.fromBytes(pngBytes, filename: "teste")
          )
      );
    }

    Dio dio = new Dio();
    dio.interceptors.add(alice.getDioInterceptor());
    return await dio
        .post(URL_WS + WS_PAGE,
        data: formData,
        options: Options(method: 'POST', responseType: ResponseType.json))
        .timeout(Duration(seconds: 2000));
//        .catchError(dioError);


  }

2 个答案:

答案 0 :(得分:1)

您必须将此for循环声明为toList()。

以下是制作方法的示例。

formData = FormData.fromMap({
  'id': '1',
  'title': 'myTitle',
  'files': [
            for (var file in listFiles)
            {await MultipartFile.fromFile(item.path, filename: 'fileName')}
             .toList()
           ]
});

我是使用MultiPartFile的优生Dio库。

答案 1 :(得分:0)

我发布了这个带有 dio 和 image_picker 依赖项的解决方案。它肯定会起作用。我为这个解决方案花了 2 天时间。

FormData formData = new FormData.fromMap({
"name": "Max",
"location": "Paris",
"age": 21,
"image[]": [
await MultipartFile.fromFile(
  _imageFile.path,
),
await MultipartFile.fromFile(
  _imageFile.path,
),
], 
});

print(FormData1().then((value) {
print(value);
 }));
response = await dio.post(

"http://143.110.244.110/radius/frontuser/eventsubmitbutton",
data: formData,
onSendProgress: (received, total) {
if (total != -1) {
  print((received / total * 100).toStringAsFixed(0) + '%');
}
},
);
 print(response);