'How to download binary file
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:
Here is my code:
void downloadFile() async {
String url = Uri.encodeFull('https://API_URL');
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?
Solution 1:[1]
Use response.bodyBytes
:
void downloadFile(File f) async {
var url = Uri.encodeFull('https://API_URL');
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.
Solution 2:[2]
if you using Dio then you can use the below code.
await dio.post(finalUrl,
options: Options(
responseType: ResponseType.bytes,
headers: headers,),
data: encodedBody,);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Richard Heap |
Solution 2 | BC TUBE |