Why dio posts empty form data?

Viewed 14131

I have a function to upload an image but the server does not receive anything and I get 500 status code. I'm sure that the server is fine. It works when I send a post request from the postman!
This is my function:

uploadPrescriptionToAll(File file, data) async {

  String convertedFilePath = await convertImage(file);

   String token = await getToken();

   Response response;
   Dio dio = Dio();
   dio.options.baseUrl = "http://x.x.x.x:x";

   FormData formData = FormData.from({
     "image":
         UploadFileInfo(new File(convertedFilePath), "image.jpg"),
     "data": data,
   });
   try {
     response = await dio.post("/api/images",
         data: formData,
         options: Options(headers: {
           "Authorization": token,
           "Content-Type": "multipart/form-data"
         }));
   } catch (e) {
     print("Error Upload: " + e.toString());
   }
   print("Response Upload:" + response.toString());
}

how can I post the file (form-data) correctly? Is there another way to do it?

2 Answers

Using Dio It's very simple by using : FormData.fromMap()

searchCityByName(String city) async {
     Dio dio = new Dio(); 
    var a = {"city": city};
    var res = await dio.post(apiSearchState, data:FormData.fromMap(a));
  }

In short, you should pass a Map<String, dynamic> object to dio.post()'s data field. For example:

response = await dio.post("/api/images",
     data: {"image": "image.jpg", "data": data});

See: https://github.com/flutterchina/dio/issues/88 for details

Related