2

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('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?

3
  • 1
    If you have the response, you already downloaded the data. I guess you just need to write it to a file instead of printing it?
    – mkrieger1
    Commented Mar 5, 2020 at 10:58
  • thank you for your reply, Can I know how to write it to a file?
    – qing
    Commented Mar 5, 2020 at 11:49
  • 1
    response.bodyBytes is the binary data. body is the same data already passed through a character recorder. The default is Latin 1 unless the content type header included an encoding parameter. Commented Mar 5, 2020 at 12:00

2 Answers 2

4

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.

8
  • Is it write like this can download the pdf and save into my phone storage?
    – qing
    Commented Mar 5, 2020 at 14:48
  • 1
    yes - create the path of the file using path_provider Commented Mar 5, 2020 at 14:56
  • I want to store my file into /storage/emulated/0/Download. How to store it? I use getExternalStorageDirectory but it store in /storage/emulated/0/Android/data/com.example.myApps/files
    – qing
    Commented Mar 5, 2020 at 15:18
  • I add save path code into my code, but now have error about Unhandled Exception: FileSystemException: Cannot open file, path = 'Instance of 'Future<Directory>'/file.pdf' (OS Error: No such file or directory, errno = 2)
    – qing
    Commented Mar 5, 2020 at 15:20
  • 2
    It seems like the problem of how to save binary data to a file is solved. @qing If there is a new problem please ask a new question instead of changing the code in your original question, which makes this answer invalid.
    – mkrieger1
    Commented Mar 5, 2020 at 15:47
0

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

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.