1

I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string

{ "imageData":"base64encoded string",
  "status":"1"
}

where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp

I cant post the complete encoding since its too lengthy. How can I convert this encoded string into a image file at server side.Actually from there I suppose to upload the image on a ftp server.

Saurabh Mishra
  • 881
  • 1
  • 8
  • 22

1 Answers1

1

Base64 uses Ascii characters to send binary files, so to retrieve your image, you basically have to decode the Base64 string back to a byte array and save it to a file.

String encoded = 'iVBORw0KGgoAAAANSUhEUg' // You complete String
encoded.replaceAll("\r", "")
encoded.replaceAll("\n", "")
byte[] decoded = encoded.decodeBase64()
new File("file/path").withOutputStream {
  it.write(decoded);
}

Edit: You problem of invalid charatercomes from the \r\n characters you have in the encoded String, you must have your base64 string in one line to decode it. I updated the sample code to do it.

aveuiller
  • 1,511
  • 1
  • 10
  • 25