如何在flutter中使用带有url编码主体的http.post下载文件?

2023-12-02

我想构建一个网络应用程序来使用 http.post 方法在 flutter 中下载 pdf 文件,我已经在互联网上搜索了它,但我仍然无法下载该文件。我已经在邮递员中尝试过使用原始 json (然后发送和下载)它可以工作,但不能在颤振中做到这一点。

Future<File> postRequest() async {
  var url = 'xxxxxxx'; <- example url

  Map dat = {
    "FileName" : "itsPdf.pdf"
  };

  File file;
  var body = json.encode(dat);

  var response = await http.post(Uri.parse(url),
      headers: {"Accept": "application/json",
          "content-type": "application/json"},
      body: body
  );

  print(response.statusCode);
  if(response.statusCode == 200) {
    file = json.decode(response.body) as File;
    return file;
  } else {
    print("ERROR");
  }
}

状态码=200

Error: FormatException: SyntaxError: Unexpected token % in JSON at position 0


我知道这可能为时已晚,但对于未来的用户来说。

要首先从服务器获取 pdf 文件,该 pdf 文件必须以 base64 进行编码。之后,您可以在 flutter 端使用 jsonDecode 来解码响应正文中的 base64 数据。

http.post("https://yoururl/api",body: json.encode({"pdf":"pdf1"}))
              .then((response) {
            print("Response status: ${response.statusCode}");
            print("Response body: ${response.body}");
// The response.body will be in json. After decoding response.body it will be in base64.

            var data = json.decode(response.body);
            var pdfData = base64.decode(data["base64"]);

          });
createPdf() async {
    var bytes = base64Decode(pdfData.replaceAll('\n', ''));
    final output = await getTemporaryDirectory();
    final file = File("${output.path}/example.pdf");
    await file.writeAsBytes(bytes.buffer.asUint8List());

    print("${output.path}/example.pdf");
    setState(() {});
}

这会将文件保存到您的应用程序临时目录中。但是您还需要将 path_provider 添加到 pubspec.yaml 中以将数据保存到应用程序目录,在 pubspec.yaml 中添加 pdf 以将 base64 字节转换为 pdf 文件,并添加 dart:convert 以对 json 和 base64 数据进行解码和编码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在flutter中使用带有url编码主体的http.post下载文件? 的相关文章

随机推荐