dart - 如何使用 Dart 的 HttpClient 上传 PDF?

标签 dart dart-io

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

任何帮助将不胜感激。

最佳答案

您可以使用MultipartRequest来自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!");
});

关于dart - 如何使用 Dart 的 HttpClient 上传 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600488/

相关文章:

flutter - 抖动中的畸形消息是什么意思?什么时候以及为什么要来?

flutter - 如何在Flutter中使用drawLine()和drawCircle()绘制4条等距离线的圆

windows - 使用dart:io将结尾写入文件

dart - 如何将Dart IO流程设置为将现有Stream用于其stdin?

flutter - flutter_bloc:构建函数返回null

dart - 如何将小部件放置在行中包含的卡片内?

Dart http_server 服务 index.html 但不拉依赖

mysql - sqljocky 查询 - 未找到方法

ubuntu - 监控并重启服务器上的 Dart 进程

dart-async - Dart await 关键字