Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to download binary file

Writer Matthew Martinez

I want to download a binary file which is PDF and save it into my device. The file comes from API response. My response.body is like this:

enter image description here

Here is my code:

void downloadFile() async { String url = Uri.encodeFull('); http.Response response = await http.post(url, headers: {"Accept": "application/json", HttpHeaders.authorizationHeader: 'Bearer '},}); print(response.body);
}

How can I use response.body to download the PDF file?

3

2 Answers

Use response.bodyBytes:

void downloadFile(File f) async { var url = Uri.encodeFull('); var response = await http.post(url, headers: {HttpHeaders.authorizationHeader: 'Bearer '},}); await f.writeAsBytes(response.bodyBytes);
}

I removed the Accept header as it made no sense. You're hinting the server that you'll expect JSON, whereas you really want a PDF.

8

if you using Dio then you can use the below code.

await dio.post(finalUrl, options: Options( responseType: ResponseType.bytes, headers: headers,), data: encodedBody,);

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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