如何在 Flutter 中使用具有正文和标头的 POST 请求从 URL 下载 .pdf 文件?

kl2*_*l23 0 dart flutter flutter-dependencies dio

我正在尝试从具有 POST 请求且主体在 Flutter 中的 URL 下载 .pdf 文件。我正在使用 Dio 插件进行网络调用。

到目前为止,这是我尝试做的事情:

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);
  }
Run Code Online (Sandbox Code Playgroud)

但据我检查,Dio 没有带下载选项的 POST 方法。

这是 Dio 文档中给出的内容:

下载文件:

response = await dio.download('https://www.google.com/', './xx.html');
Run Code Online (Sandbox Code Playgroud)

但这里我们不能添加请求正文或标头。

另外,我需要将文件下载到设备中的特定文件夹,例如内部存储中的 /downloads 文件夹。下载成功后,我们可以直接从该屏幕打开文件。

如何进行?我对 Flutter 很陌生。

awa*_*aik 5

您可以使用options参数。您还可以添加 cookie 或其他参数。

response = await dio.download(
  'https://www.google.com/', './xx.html',
  options: Options(
    headers: {'cookie': 'any_cookie'}, 
    method: 'POST',
  ),
);
Run Code Online (Sandbox Code Playgroud)