flutter dio upload files [pdf/ docs] flutter dio upload files [pdf/ docs] dart dart

flutter dio upload files [pdf/ docs]


If you want to upload the file you can convert multipart array before calling API function because even if you put await in form data dio response will not wait for formdata object or you can use MultipartFile.fromFileSync() to get rid of await.

Let me show you in a simple way using my example. try to understand.

Multipart conversion

List multipartArray = [];for (var i = 0; i < pathNames.length; i++){   multipartArray.add(MultipartFile.fromFileSync(pathNames[i], filename:    basename(pathNames[i])));}

Api side

static Future<Response> createPostApi(multipartArray) async {    var uri = Uri.parse('http://your_base_url/post');    return await Dio()        .post('$uri',            data: FormData.fromMap({              "title": "from app2",              "description": "app upload test",              "files": multipartArray            }))        .catchError((e) {      print(e.response.data);      print(e.response.headers);      print(e.response.request);    });  }


Change formdata with following rest is fine

   import 'package:path/path.dart' as pathManager;    import 'package:mime/mime.dart' as mimeManager;FormData formdata = FormData(); formdata.add(          "files",          [UploadFileInfo(img, pathManager.basename(img.path),          contentType:              ContentType.parse(mimeManager.lookupMimeType(img.path)))]);


// here attachmentFile is File instance, which is set by File PickerMap<String, dynamic> _documentFormData = {};if (attachmentFile != null) {        _documentFormData['document_file'] = MultipartFile.fromFileSync(attachmentFile.path);}FormData formData = FormData.fromMap(_documentFormData);try {      var response = await dio.post("http://url/api/upload",          data: formData, onSendProgress: (int send, int total) {        print((send / total) * 100);      });      print(response);    } on DioError catch (e) {      if (e.response != null) {        print(e.response.data);        print(e.response.headers);        print(e.response.request);      } else {        print(e.request.headers);        print(e.message);      }    }