'unable to send post request in dio - flutter
I'm trying to send Post request from Flutter(dio) to my Flask Restful API and I want to give the request body in form-data because an image file needs to be sent. The Flask app with the help of Postman - it works fine with my Postman's form-data, but when I tried with Flutter's dio package to Post the form-data to Flask gets an error in Flask.
The dio code is :
Future<List> apiRequest(int N ,File file) async {
String url = "http://10.0.2.2:5000/";
// HttpClient httpClient = new HttpClient();
Post _post = Post();
var bytes = await file.readAsBytes();
//TODO : dio post request
var dio = new Dio();
MultipartFile multipartFile = new MultipartFile.fromBytes(bytes);
FormData formData = new FormData();
dio.options.headers = {"content-type" :"multipart/form-dataitem"};
formData.fields.add(MapEntry("index" , N.toString()));
formData.files.add(MapEntry("file",multipartFile));
print(formData);
await dio.post(url, data: formData,options: Options(
method: 'POST',
responseType: ResponseType.json // or ResponseType.JSON
)).then((response){
//response stuffs
});
Postman request which works fine
Flask statements that uses this form-data
fromJson = request.form['index']
Img = request.files['file']
The error in the Flask console
{exception: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.}
Solution 1:[1]
The error is thrown from the server because it's unable to identify the MediaType of the MultipartFile. You need to declare the type and subtype for the the File that you're using on the HTTP Request.
MultipartFile multipartFile = MultipartFile.fromFile(
file.path,
filename: fileName,
contentType: MediaType('type', 'subtype'), //important
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Omatt |