Flutter http 400 error when sending an XFile Image

Issue

I want to send a jpg file from my flutter app to .Net backend. I’m using http package.

My code is as follows:

var uri = Uri.parse('$url/upload/$id');
var request = http.MultipartRequest('POST', uri);

var headers = {'accept': '*/*', 'Content-Type': 'multipart/form-data'};

request.headers.addAll(headers);

var x = await file.readAsBytes();
var mFile = http.MultipartFile.fromBytes('file', x);
request.files.add(mFile);

var response = await request.send();

Here file is an XFile file from package cross_file.

Unfortunately I get an error code – 400 "Bad request".

On the backend side code looks as follows

 [HttpPost("/upload/{id}")]
 public IActionResult UploadImage(IFormFile imageFormFile, [FromRoute] Guid id)
 {
     // program does not even enter the function
 }

I’ve tested this using Swagger and it works, it generates following curl:

    curl -X 'POST' \
  'http://localhost:44383/apiname/f7765448-be93-4e72-b62e-04623b4ccdb1' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'imageFormFile=@sample.jpg;type=image/jpeg'

I’ve searched some forums and tutorials, but nothing works.

I’ve tried adding the file using fromBytes, fromPath and fromString, none worked.

I’ve tried experimenting with different combinations of headers and fields, this didn’t work either. In particular I’ve tried to add fields "imageFormFile" and "type", as in Swagger curl, but it didn’t work as well.

I’ve also tried to rewrite this using dio, but got the same result (also I’d rather stick to http, as the rest of my project uses it).

Solution

Future uploadRequest(String url, String filePath) async {
   final dio = Dio();
   dio.options.contentType = "multipart/form-data";
   final multiPartFile = await MultipartFile.fromFile(
     filePath,
     filename: filePath.split('/').last,
   );
   FormData formData = FormData.fromMap({
     "file": multiPartFile,
   });
   final response = await dio.post(
     url,
     data: formData,
   );
   return response.data;
}

This is 100% working solution but with dio package as I prefer it over http. But It doesn’t mean that with http it is impossible.

IMPORTANT: formData could be different according to your API

Answered By – Jakhongir Anasov

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *