How to pass image file to the body of Http request (POST) in Flutter?

898

You should use MultiPart post method. Take a look at this.

Share:
898
Toujo
Author by

Toujo

Updated on January 01, 2023

Comments

  • Toujo
    Toujo about 1 year

    I Took a variable in my State File? image;

    Then Accesing image from my device

      void filePicker() async {
        final File? selectedImage =await ImagePicker.pickImage(source: ImageSource.gallery);
        print(selectedImage!.path);
        setState(() {
          image = selectedImage;
        });
      }
    

    Then tyring to pass the image file along with other http body parameters. If I didn't pass the image file, then the API didn't show any error. But I need to pass the image file to get the correct result. As I Explicitly throw Exception, so its throwing exception like Faild to fetch and message in ScaffoldMessenger --> Somthing went wrong

     Future<void> SaveCustomTestBooking() async {
    var jsonResponse;
    if (EncUserId.isNotEmpty) {
      var postUri = Uri.parse("http://medbo.digitalicon.in/api/medboapi/SaveCustomTestBooking");
      var request = http.MultipartRequest('POST', postUri);
      request.fields['VisitDate'] = _selectedDate;
      request.fields['EncUserId'] = EncUserId;
      request.files.add(new http.MultipartFile.fromBytes('image',await File.fromUri(Uri.parse(image!.path)).readAsBytes(),contentType: new MediaType('image', 'jpeg')));
    
      request.send().then((response) {
        if (response.statusCode == 200) {
          print("Uploaded!");
          Navigator.push(context,MaterialPageRoute(builder: (context) => DieticianAfterDateSelectPage(rresponse:DieticianEncBookingIdModel.fromJson(jsonResponse),)));
        } else {
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text("Somthing went wrong")));
          throw Exception("Faild to fetch");
        }
      });
    }
    

    }

    • Mohamed Sayed
      Mohamed Sayed over 2 years
      did you print out base64Encode(image!.readAsBytesSync()) to see if already contains 'data:image/jpg;base64,'
    • Toujo
      Toujo over 2 years
      No . But Instead Im displaying the image in my device. and its showing the image
    • Toujo
      Toujo over 2 years
      I also try 'UserFile':image.toString(), same error... Its necessary to convert the image to base64 ?