How can I upload a PDF using Dart's HttpClient?


I need to post a PDF file to a remote REST API, and I can’t for the life of me figure it out. No matter what I do, the server responds that I have not yet associated an object with the file parameter. Let’s say that I have a PDF called test.pdf. This is what I’ve been doing so far:

// Using an HttpClientRequest named req

req.headers.contentType = new ContentType('application', 'x-www-form-urlencoded');
StringBuffer sb = new StringBuffer();
String fileData = new File('Test.pdf').readAsStringSync();
return req.close();

Thus far, I’ve tried virtually every combination and encoding of the data that I write() to the request, but to no avail. I’ve tried sending it as codeUnits, I’ve tried encoding it using a UTF8.encode, I’ve tried encoding it using a Latin1Codec, everything. I’m stumped.

Any help would be greatly appreciated.


You can use MultipartRequest from the http package :

var uri = Uri.parse("");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = '';
request.files.add(new http.MultipartFile.fromFile(
    new File('build/package.tar.gz'),
    contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
  if (response.statusCode == 200) print("Uploaded!");

Answered By – Alexandre Ardhuin

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *