【发布时间】:2021-11-28 04:33:50
【问题描述】:
现在我正在使用 http 包创建一个使用 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包
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返回一个空响应。
【问题讨论】: