![](/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.