【问题标题】:How can I upload a PDF using Dart's HttpClient?如何使用 Dart 的 HttpClient 上传 PDF?
【发布时间】:2014-05-01 06:48:17
【问题描述】:

我需要将 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 对其进行编码,一切。我被难住了。

任何帮助将不胜感激。

【问题讨论】:

    标签: dart dart-io


    【解决方案1】:

    您可以使用http package 中的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!");
    });
    

    【讨论】:

    • 谢谢,这非常有帮助!您是否偶然知道如何使用 http 包向POST 添加凭据?使用标准 HttpClient 相当简单,但我没有看到使用 http 库是如何做到的。
    • 对不起,我不知道。我认为你必须手动添加好的 Header.
    • 为什么在 '.fromFile' 处出现错误?我错过了什么吗?
    【解决方案2】:
      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);
        });
      }
    

    我使用文件选择器来选择文件。 这是pick文件的代码。

    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颤振库。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-30
        • 2023-03-14
        • 2015-02-10
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        相关资源
        最近更新 更多