[英]Image Upload with flutter http MultipartFile
現在我正在創建一個 function 用於使用http ZEFE90A8E6034A7C840E7D8F8Z 上傳帶有 Flutter 的圖像
這是上傳圖片到服務器的代碼
Future<String> uploadNewImage(String imagePath) async {
var postUri = Uri.parse("https://test.vahupu.com/g2.php?mode=fileupload");
var request = http.MultipartRequest("POST", postUri);
request.files.add(
await http.MultipartFile.fromPath(
"file",
imagePath,
filename: imagePath.split("/").last,
),
);
var response = await request.send();
if (response.statusCode == 200) {
var responseString = await response.stream.bytesToString();
var responseJson = json.decode(responseString);
if (responseJson.isEmpty) {
showErrorDialog("Server Error");
return "";
} else {
showErrorDialog("Image Uploaded Succesfully");
return responseJson["filepath"];
}
} else {
showErrorDialog("Something Went Wrong");
}
return "";
}
imagePath 來自 image_picker package
Future _getImgFromGallery() async {
XFile? image = await picker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
);
if (image != null) {
String imageName = await uploadNewImage(
image.path,
);
if (imageName != "") {
widget.addOrRemoveImage(imageNameList, image.path);
}
}
}
這個 api 端點適用於我的 Thunderclient(POSTMAN 的替代方案)。
但是該代碼不適用於 flutter 應用程序,並且 API 返回一個空響應。
最后我得到了解決方案......
在服務器端 api 使用 php 中的$_FILES["file"]["type"]
操作驗證文檔
但是 http.MultipartFile function 使用application/octet-stream
發送數據
所以 if 條件沒有在服務器端執行。 所以 api 返回一個空的響應。
content-type: MediaType.parse("image/png")
我將此行添加到 http.MultipartFile function。 所以我解決了這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.