0
votes

I need to send an image to backend which supports the upload of the media in the request body as binary.

enter image description here

If I try to upload an image through Postman using the binary body option, with header value as 'Content-Type' : 'image/jpg', the image is getting uploaded correctly and I'm able to access the uploaded media via the response URL from backend.

Same thing, when I try it from Flutter, I'm getting a 200 response code, but the uploaded file is corrupted I think. Below is the code I'm using:

var response = await http.put(URL),
    headers: {
      'Content-Type': "image/jpg",
      'Accept': "*/*",
      'Content-Length': File(portraitImagePath).lengthSync().toString(),
      'Connection': 'keep-alive',
    },
    body: File(portraitImagePath).readAsBytesSync(),
    );

Please help me to identify the issue and complete this upload process.

1

1 Answers

1
votes

Updating the working code so that it may help anyone who is facing the same issue.

var response = await http.put(URL),
headers: {
  'Content-Type': "image/jpg"
},
body: await File(portraitImagePath).readAsBytes(),
);

I missed including await while reading the Image and also changed to readAsBytes() from readAsBytesSync()