OWM
OWM

Reputation: 33

POST image to web service with Flutter

I am currently using Flutter and Dart to try to send an image to a web service, after which I wait for a JSON response. The below links show the Postman request that I am trying to mimic.

An image of Postman with the headers required

An image of Postman with the body

I think the issue I am having is either not setting the headers of my request correctly, or not encoding the image correctly.

Currently I am getting a HTTP 400 error.

I have tried following these suggested solutions on StackOverflow but have been getting the HTTP 400 error.

Any help would be much appreciated!

Upvotes: 1

Views: 2558

Answers (1)

Richard Heap
Richard Heap

Reputation: 51750

Try this. I'd suggest creating yourself a plain Dart project, if you haven't already. This way you can test things without the need of the phone emulator, etc.

main() async {
  http.MultipartRequest request =
      new http.MultipartRequest('POST', Uri.parse(url));

  request.headers['Prediction-Key'] = '3f4a......'; // todo - insert real value

  request.files.add(
    new http.MultipartFile.fromBytes(
      'image',
      bytes,
      filename: 'somefile', // optional
      contentType: new MediaType('image', 'jpeg'),
    ),
  );

  http.StreamedResponse r = await request.send();
  print(r.statusCode);
}

If the file is on disk, not in memory, then use the fromPath named constructor instead. Experiment with different media types. I've used image/jpeg, but you could try application/octet-stream.

As an aside, in your first screenshot you show a content type, but Postman ignores this as the overall content type is overridden by multipart-form. Uncheck that row in Postman to prove this.

There was another question recently on SO, where the server was incorrectly expecting headers to be case sensitive. In postman, try again with lowercase prediction-key to prove that the server doesn't mind lowercase headers (which is what Dart uses).

Upvotes: 4

Related Questions