如何使用Dart的HttpClient上传PDF文件?

8

我需要将一个PDF文件发布到远程REST API,但是我却无法弄清楚该如何操作。无论我做什么,服务器都会回应我还没有将对象与file参数相关联。假设我有一个名为test.pdf的PDF文件,这是迄今为止我一直在做的事情:

// 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();

到目前为止,我已经尝试了几乎每一种数据组合和编码方式作为我write()请求的数据,但都没有成功。我试过将其发送为codeUnits,尝试使用UTF8.encode进行编码,也尝试使用Latin1Codec进行编码,但一切都无济于事。我很困惑。

非常感谢任何帮助。

3个回答

9

你可以使用来自http packageMultipartRequest

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

1
谢谢,这非常有帮助!你是否碰巧知道如何使用http包在POST请求中添加凭据?使用标准的HttpClient相当简单,但我不知道如何在http库中实现。 - lucperkins
抱歉,我不知道。我认为您必须手动添加正确的_Header_。 - Alexandre Ardhuin
为什么我在‘.fromFile’处出现错误?我漏掉了什么吗? - ABM

0

尝试使用 multipart/form-data 标头而不是 x-www-form-urlencoded。这应该用于二进制数据,你能展示完整的 req 请求吗?


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

我使用文件选择器来选择文件。 以下是选择文件的代码。

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

    }
  }

这里是file_picker Flutter 库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接