0
votes

I am Trying to Upload a image to server, by the way I have used Image Cropper and Picker Libraries. it works fine, but during API Call I need to encode as base64, here the encoded string is wrong comparing to online image-to-base64 encode tool. so Server Failed to Save the data even if it Saved it seems Invalid Image. Please Help me to resolve this problem.

I have checked in API using Postman (online base64 image tools), it works fine.

Code :

Future<void> uploadProfileImage() async {
    if (imageFile == null) return;
    String imageFileName = imageFile.path.split("/").last;
    // String base64ProfileImage = base64.encode(imageFile.readAsBytesSync()); // this gives problem
    

    List<int> imageBytes = imageFile.readAsBytesSync();//
    String encodedFile = base64.encode(imageBytes);//this also gives same problem
log(encodedFile);  
......

Other Stuff
    
  }

ScreenShot

Online Convert Tool Starts With these Characters

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANcAAADXCAYAAACJfcS1AAA6BUlEQVR42u19B5QU1dbu3H/dtLw55/Svdd979/03vWtCVKKIiqCiKDmIJC9BEEYkM+Q85JyGOAzBITNkEAdUMiiCkpGcMwj71Xdg9z1dc6rqVHd1d3V31Vp7wcx0VzjnfLX3/nY4GXP3H6VUkJGTJ1KrJ/8mZFjFR2hN/TIpLcvrlqICTVlZr3Tc7mt85WKUWfLvYh66NqhOs3buoVRZY24lIxUeYmzerBCwcl4pnjIAAjAW1SpBCw2ZV/
1

1 Answers

0
votes

i have had the same issue and i resolved it like this

Future<String> tobase64(File image) async {
  // I encode files to base64 format
  List<int> imgBytes = await image.readAsBytes();
  String base64img = base64Encode(imgBytes);
  return base64img;
}


  Future getImage(
    ImageSource source,
  ) async {
    final pickedFile = await picker.getImage(source: source);

    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });

      List<String> _splitted = pickedFile.path.split('.');
// this is the  important line on formating
      _process("data:image/${_splitted.last};base64,");
    }
  }



// this method process and formats your base64 data to the standard format
 Future _process(String format) async {
    baseSix4 = format + await tobase64(_image);

  }