我想將圖片作為多部分檔案發送到服務器。
首先我嘗試使用http.post:
var response = await http.post(
Uri.parse('url.php'),
headers:{ "Content-Type":"multipart/form-data" } ,
body: {
"fichier": base64img
}
);
我收到了這個錯誤:
錯誤狀態:無法設定內容型別為“multipart/form-data”的請求的正文欄位。
查看這個主題的答案,我嘗試使用dio 包:
var dio = Dio();
var formData = FormData.fromMap({
'fichier': await MultipartFile.fromFile(filePath, filename: 'upload')
});
var response = await dio.post(
'url.php',
data: formData
);
我收到了這個錯誤:
錯誤:不支持的操作:僅當 dart:io 可用時才支持 MultipartFile。
一個已經在這里公開的問題。
最后,我嘗試使用http 包中的MultipartRequest:
var url = Uri.parse('url.php');
var request = new http.MultipartRequest("POST", url);
request.files.add(
await http.MultipartFile.fromPath(
"fichier",
filePath
)
);
request.send().then((response) => print(response));
得到與 dio 包完全相同的錯誤。
如果有人作為解決方案,我很樂意接受。
uj5u.com熱心網友回復:
使用 http 包并使用fromBytesintead獲取影像fromPath:
final uri = Uri.parse('https://myendpoint.com');
var request = new http.MultipartRequest('POST', uri);
final httpImage = http.MultipartFile.fromBytes('files.myimage', bytes,
contentType: MediaType.parse(mimeType), filename: 'myImage.png');
request.files.add(httpImage);
final response = await request.send();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443170.html
