3

I want to build a web app to download a pdf file in flutter using http.post method, I have already searched the internet for it but I still can't download the file. I have already tried in postman with raw json (then send and download) it works but can't do it in flutter.

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");
  }
}

status code = 200

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

guness
  • 6,336
  • 7
  • 59
  • 88
Kevin Malix
  • 65
  • 2
  • 4

1 Answers1

4

I know this might be too late but for future users.

To get a pdf file from your server first the pdf file must be encoded in base64. After that you can use jsonDecode in flutter side to decode the base64 data from body of response.

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(() {});
}

And this will save the file to your application temporary directory. But you will also need to add path_provider to your pubspec.yaml for saving data to application directory, pdf in pubspec.yaml to convert the base64 bytes to pdf file, and dart:convert to decode and encode the json and base64 data.

Just a Person
  • 1,276
  • 1
  • 5
  • 23