8

我需要将 PDF 文件发布到远程 REST API,但我终生无法弄清楚。无论我做什么,服务器都会响应我尚未将对象与file参数关联。假设我有一个名为test.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,我尝试使用 a 对其进行编码UTF8.encode,我尝试使用 a 对其进行编码Latin1Codec,一切。我难住了。

任何帮助将不胜感激。

4

3 回答 3

9

您可以使用http 包中的MultipartRequest

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!");
});
于 2014-03-24T08:30:02.253 回答
0

尝试使用multipart/form-data标题而不是x-www-form-urlencoded. 这应该用于二进制数据,您也可以显示您的完整req请求吗?

于 2014-03-24T04:59:49.980 回答
0
  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颤振库。

于 2021-02-06T19:12:30.537 回答