How to download binary file
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:
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?
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.
if you using Dio then you can use the below code.
await dio.post(finalUrl, options: Options( responseType: ResponseType.bytes, headers: headers,), data: encodedBody,);