Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload images and file to a server in Flutter?

I use a web service for image processing , it works well in Postman:

postman screenshot

Now I want to make http request in flutter with Dart:

import 'package:http/http.dart' as http;  static ocr(File image) async {     var url = '${API_URL}ocr';     var bytes = image.readAsBytesSync();      var response = await http.post(         url,         headers:{ "Content-Type":"multipart/form-data" } ,         body: { "lang":"fas" , "image":bytes},         encoding: Encoding.getByName("utf-8")     );      return response.body;    } 

but I don't know how to upload the image file, in above code I get exception: Bad state: Cannot set the body fields of a Request with content-type "multipart/form-data".
How should I write the body of request?

like image 740
Mneckoee Avatar asked Mar 06 '18 07:03

Mneckoee


People also ask

How do you send pictures to server on Flutter?

First, add the image_picker Flutter package as a dependency by adding the following line in your pubspec. yaml file. Now write the function for pick image from Gallery. The optional parameter imageQuality accepts any value between 0 to 100, you can adjust it according to the size and quality required by your app.


2 Answers

Your workaround should work; many servers will accept application/x-www-form-urlencoded as an alternative (although data is encoded moderately inefficiently).

However, it is possible to use dart:http to do this. Instead of using http.post, you'll want to use a http.MultipartFile object.

From the dart documentation:

var request = new http.MultipartRequest("POST", url); request.fields['user'] = '[email protected]'; request.files.add(http.MultipartFile.fromPath(     'package',     'build/package.tar.gz',     contentType: new MediaType('application', 'x-tar'), )); request.send().then((response) {   if (response.statusCode == 200) print("Uploaded!"); }); 
like image 87
rmtmckenzie Avatar answered Sep 19 '22 04:09

rmtmckenzie


I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio is very easy to use, in this case you can:

Sending FormData:

FormData formData = new FormData.from({    "name": "wendux",    "file1": new UploadFileInfo(new File("./upload.jpg"), "upload1.jpg") }); response = await dio.post("/info", data: formData) 

More details please refer to dio。

like image 29
wendu Avatar answered Sep 19 '22 04:09

wendu