Little Monkey
Little Monkey

Reputation: 6157

Flutter: upload image using binary body

I want to upload a file using binary body like in the screenshot:

screenshot

So far I just have:

      save() async {
         http.put(url,headers:headers, body: );

Upvotes: 7

Views: 8365

Answers (3)

ali sampson
ali sampson

Reputation: 467

If you're using http.Request, the you can use the code below:

var request = http.Request('PUT', Uri.parse(url));

request.bodyBytes = file.readAsBytesSync(); // set file bytes to request.bodyBytes  

http.StreamedResponse response = await request.send();

var responseJson;

if (response.statusCode == 200) {
  responseJson = 'Upload success';
} else {
  responseJson = 'Upload failed.';
}

Upvotes: 0

Sher Ali
Sher Ali

Reputation: 5793

You can use this for upload Image

Future uploadImage(File imageFile)async{
  var stream= new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
  var length= await imageFile.length();
  var uri = Uri.parse("Image upload url");
  var request = new http.MultipartRequest("POST", uri);
  var filename = "Your image name";
  var multipartFile = new http.MultipartFile("image", stream, length, filename: basename(filename));
  request.files.add(multipartFile);
  var response = await request.send();
  if(response.statusCode==200){
    print("Image Uploaded");
  }else{
    print("Upload Failed");
 }
}

Upvotes: -2

Xavier
Xavier

Reputation: 4025

The body parameter of the put method accepts a List<int> that will be used as a list of bytes

From the http API reference: https://pub.dev/documentation/http/latest/http/put.html

body sets the body of the request. It can be a String, a List or a Map. If it's a String, it's encoded using encoding and used as the body of the request. The content-type of the request will default to "text/plain".

If body is a List, it's used as a list of bytes for the body of the request.

If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.

Examples to send a file:

main() async {
  await put(url, body: File('the_file').readAsBytesSync());
}

Upvotes: 12

Related Questions