0

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). Screenshot for image uploading with Thunderclient

But the code does not works with the flutter app, and the API returns an empty response.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.