8

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();
sb.write('file=$fileData');
req.write(sb.toString());
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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
lucperkins
  • 768
  • 1
  • 7
  • 15

3 Answers3

9

You can use MultipartRequest from the http package :

var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'john@doe.com';
request.files.add(new http.MultipartFile.fromFile(
    'package',
    new File('build/package.tar.gz'),
    contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
  if (response.statusCode == 200) print("Uploaded!");
});
balu k
  • 3,515
  • 2
  • 14
  • 29
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 1
    Thanks, that's extremely helpful! Do you by chance know how to add credentials to a `POST` using the http package? That's fairly trivial using the standard `HttpClient`, but I'm not seeing how that's done using the http library. – lucperkins Mar 24 '14 at 15:12
  • Sorry I don't know. I think you have to manually add the good _Header_. – Alexandre Ardhuin Mar 24 '14 at 15:28
  • Why am I getting error at '.fromFile'? Am I missing something? – ABM Jun 21 '21 at 10:30
0

Try using the multipart/form-data header rather than x-www-form-urlencoded. This should be used for binary data, also can you show your full req request?

Padmal
  • 458
  • 5
  • 15
user2685314
  • 1,059
  • 6
  • 9
-1
  void uploadFile(File file) async {

    // string to uri
    var uri = Uri.parse("enter here upload URL");

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

    // if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
    request.fields["user_id"] = "text";

    // multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
    MultipartFile multipartFile = await http.MultipartFile.fromPath(
          'idDocumentOne_1',
          file.path
    );

    // add file to multipart
    request.files.add(multipartFile);

    // send request to upload file
    await request.send().then((response) async {
      // listen for response
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });

    }).catchError((e) {
      print(e);
    });
  }

I used file picker to pick file. Here is the codes for pick file.

Future getPdfAndUpload(int position) async {

    File file = await FilePicker.getFile(
      type: FileType.custom,
      allowedExtensions: ['pdf','docx'],
    );

    if(file != null) {

      setState(() {

          file1 = file; //file1 is a global variable which i created
     
      });

    }
  }

here file_picker flutter library.

Supun Dewapriya
  • 695
  • 11
  • 13