![](/img/trans.png)
[英]How can I convert the response of a http.MultipartRequest POST method in a map<String, dynamic> in Flutter?
[英]How to cancel ongoing file upload sent with http.MultipartRequest() in Flutter?
我正在尝试在Flutter应用程序中为文件上传添加取消功能。 我目前正在使用http package
http.MultipartRequest()
上传文件。 我尝试用CancelableOperation
包装上传文件,但它只会取消Flutter应用程序中的内部进程,并且文件仍成功上传到Firebase Storage服务器。
我阅读了有关使用http.Client()
并在http请求完成后将其关闭的http包上的http.Client()
。 我正在考虑使用http.Client()
上传文件,然后使用http.Client().close()
关闭该文件以取消http请求。
但是,我还没有找到使用http.Client
上传文件的正确方法。 我在Google和stackoverflow上进行了浏览,但是所有帖子都建议使用http.MultipartRequest()
。 帖子之一
因此,我的问题是:1.是否可以从Flutter中的http包中取消使用http.MultipartRequest()
发送的上传文件? 2.我是否在尝试使用http.Client()
的正确轨道上? 还是有更好的方法来做到这一点? 3.如果唯一的方法是使用http.Client()
,那么您能告诉我如何使用http.Client()
上传文件吗? 因为它只有post()
而没有multipartrequest()
。
抱歉,长文本。 请帮忙。 谢谢!
包http
在HTTPClient
使用HTTPClient
。 它将底层客户端包装在IOClient
。 http
的大多数方法(如get
和post
)都允许您传入自己的客户端,但是MultipartRequest
不允许(它为每个请求创建一个)。
最简单的解决方案似乎是对其进行子类化。
import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;
class CloseableMultipartRequest extends http.MultipartRequest {
http.IOClient client = http.IOClient(HttpClient());
CloseableMultipartRequest(String method, Uri uri) : super(method, uri);
void close() => client.close();
@override
Future<http.StreamedResponse> send() async {
try {
var response = await client.send(this);
var stream = onDone(response.stream, client.close);
return new http.StreamedResponse(
new http.ByteStream(stream),
response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase,
);
} catch (_) {
client.close();
rethrow;
}
}
Stream<T> onDone<T>(Stream<T> stream, void onDone()) =>
stream.transform(new StreamTransformer.fromHandlers(handleDone: (sink) {
sink.close();
onDone();
}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.