使用 Dart 通过 POST 发送文件(仅限服务器端)
Send a file via POST using Dart (server-side only)
我正在开发 Telegram Bot,我需要通过 POST 将文件作为附件发送给用户(例如 .txt 文件)。对此,我有两个问题:
- 我应该使用哪种文件类型来发送文件?我听说过
流,但我不确定;
具有正确的文件类型,如何将其作为参数发送给
url POST?我尝试了 http 库和内置解决方案。
这是我现在正在使用的代码片段:
Future<dynamic> sendRequest(String method, url, {json}) async {
BaseClient bs = new IOClient();
var request = new Request(method, url);
request.headers['Content-Type'] = 'application/json';
request.body = JSON.encode(json);
var streamedResponse = await bs.send(request);
var response = await Response.fromStream(streamedResponse);
var bodyJson;
try {
bodyJson = JSON.decode(response.body);
} on FormatException {
var contentType = response.headers['content-type'];
if (contentType != null && !contentType.contains('application/json')) {
throw new Exception(
'Returned value was not JSON. Did the uri end with ".json"?');
}
rethrow;
}
if (response.statusCode != 200) {
if (bodyJson is Map) {
var error = bodyJson['error'];
if (error != null) {
throw error;
}
}
throw bodyJson;
}
return bodyJson;
}
有什么想法吗?
我推断您正在使用 Dart Pub http
包。简要查看文档,似乎支持 multi part 和 streaming 上传。请参阅 MultipartRequest
和 StreamedRequest
类。 (我自己没有用过这些,但它们看起来很简单。)
https://www.dartdocs.org/documentation/http/0.11.3%2B9/http/http-library.html
这个问题可能有助于理解 HTTP multipart/form-data
文件上传。 。其他人可能能够指出有关流式上传的良好资源。
我正在开发 Telegram Bot,我需要通过 POST 将文件作为附件发送给用户(例如 .txt 文件)。对此,我有两个问题:
- 我应该使用哪种文件类型来发送文件?我听说过 流,但我不确定;
具有正确的文件类型,如何将其作为参数发送给 url POST?我尝试了 http 库和内置解决方案。
这是我现在正在使用的代码片段:
Future<dynamic> sendRequest(String method, url, {json}) async { BaseClient bs = new IOClient(); var request = new Request(method, url); request.headers['Content-Type'] = 'application/json'; request.body = JSON.encode(json); var streamedResponse = await bs.send(request); var response = await Response.fromStream(streamedResponse); var bodyJson; try { bodyJson = JSON.decode(response.body); } on FormatException { var contentType = response.headers['content-type']; if (contentType != null && !contentType.contains('application/json')) { throw new Exception( 'Returned value was not JSON. Did the uri end with ".json"?'); } rethrow; } if (response.statusCode != 200) { if (bodyJson is Map) { var error = bodyJson['error']; if (error != null) { throw error; } } throw bodyJson; } return bodyJson; }
有什么想法吗?
我推断您正在使用 Dart Pub http
包。简要查看文档,似乎支持 multi part 和 streaming 上传。请参阅 MultipartRequest
和 StreamedRequest
类。 (我自己没有用过这些,但它们看起来很简单。)
https://www.dartdocs.org/documentation/http/0.11.3%2B9/http/http-library.html
这个问题可能有助于理解 HTTP multipart/form-data
文件上传。 。其他人可能能够指出有关流式上传的良好资源。