7

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: );
2
  • What does it do now? And what's the issue? Commented May 20, 2019 at 8:15
  • No issue, the only problem is that I don 't know how to specify that I want to insert a binary body. Commented May 20, 2019 at 8:17

3 Answers 3

12

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

Worked for me. I was uploading the file on AWS3 bucket and not able to send file over the server but this solution helped me lot. Thanks @Xavier.
Worked well :+1
You are a life saver. I have been on this for about 3 days now. Thank you.
0

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.';
}

Comments

-2

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");
 }
}

1 Comment

What is DelegatingStream?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.