![](/img/trans.png)
[英]How can I convert the response of a http.MultipartRequest POST method in a map<String, dynamic> in Flutter?
[英]How to convert multiPartRequest's response into normal http response in flutter?
我必須發送 api 請求才能將文件上傳到服務器。
模式:repo,提供者服務
由於 multipartRequest 發送的響應,我關注失敗
如何將請求轉換為正常的獲取/發布請求?
Future mutliPartPostRequest(
{required String method,
required String url,
Map<String, String>? headers,
File? file,
String? document,
Map? data}) async {
Map<String, dynamic> jsonResponse;
try {
var request = http.MultipartRequest(method, Uri.parse(url));
data!.forEach((key, value) {
request.fields[key] = value.toString();
});
request.headers['Authorization'] = headers!['authorization']!;
/// [FILTERING] : the null image if there are no photos in the request it will skip adding the photo in the request
if (file != null) {
var picture = await http.MultipartFile.fromPath("photo", file.path);
request.files.add(picture); //adds the photo to the request
}
// Checking the document if it is empty, if it is empty it will skip to add the document in the request
if (document != null) {
var doc = await http.MultipartFile.fromPath('document', document);
request.files.add(doc); // adds the document to the request
}
///Our case starts from this line, while sending multipart request, the response we get is quite different than the normal json data response.
// response => stores the response got
var response = await request.send().timeout(const Duration(seconds: 10)); //sends the request body to the server
// result => coverts the multipart response got from the server to the normal request
var result = await http.Response.fromStream(response);
jsonResponse = returnResponse(result); /// returns the response according to the status code from [returnResponse] function
} on SocketException {
throw FetchDataException({"detail": "No Internet Connection"});
}
return jsonResponse;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.