Home > Software engineering >  How to download a .pdf file from an URL with POST Request having a body and headers in Flutter?
How to download a .pdf file from an URL with POST Request having a body and headers in Flutter?

Time:01-31

I am trying to download a .pdf file from an URL having a POST request with body in Flutter. I am using Dio plugin for network calls.

Here is what I tried to do so far:

Dio dio = Dio();
late Response response;


Future<APIResponse> downloadFile({token}) async {
    await dio
        .post('https://www.example.com/sample/download',
            data: {
              {"month": "January", "year": "2022"}
            },
            options: Options(
              headers: {
                'Authorization': 'Bearer $token',
              },
            ))
        .then((value) {
      if (value.statusCode == 200) {
        response = value;
        // here I need the file to be downloaded
        // specific folder would be /downloads folder in Internal Storage
      }
    });
    return APIResponse.fromJson(response.data);
  }

But Dio doesn't have POST method with download option, as far as I have checked.

This is what is given in Dio docs:

For downloading a file:

response = await dio.download('https://www.google.com/', './xx.html');

But here we cannot add request body or headers.

Also I need to download the file to a specific folder in the device such as /downloads folder in internal storage. When download is successful, we can open the file right from that screen.

How to proceed? I am very new to Flutter.

CodePudding user response:

You can use options parameter. You also can add cookie or other parameters.

response = await dio.download(
  'https://www.google.com/', './xx.html',
  options: Options(
    headers: {'cookie': 'any_cookie'}, 
    method: 'POST',
  ),
);
  •  Tags:  
  • Related