How can I upload a PDF using Dart's HttpClient

2019-01-18 07:30发布

问题:

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.

回答1:

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


回答2:

I'd like to recommend dio package to you, dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio is very easy to use, in your case you can:

Sending FormData:

FormData formData = new FormData.from({
 "name": "wendux", // Other Field
 "file1": new UploadFileInfo(new File("./upload.pdf"), "upload1.pdf"),
 "file2": new UploadFileInfo(new File("./upload.txt"), "upload2.txt")
});
response = await dio.post("/info", data: formData);

More details please refer to dio in Github: https://github.com/flutterchina/dio.



回答3:

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



标签: dart dart-io