Now I am creating a function for uploading image with Flutter by using http package
This is the code for uploading image to server
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 "";
}
The imagePath is comes from the 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);
}
}
}
This api endpoint works fine with my Thunderclient(altnertative for POSTMAN).
But the code does not works with the flutter app, and the API returns an empty response.
Finally I Got the solution...
In server side api validate the document by using $_FILES["file"]["type"]
operation in php
but the http.MultipartFile function sends the data with application/octet-stream
so the if condition not executed in the server side. so the api returns an empty repsonse.
content-type: MediaType.parse("image/png")
I added this lines to the http.MultipartFile function. so i resolved this issue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.