I'm writing a webservice using spring.
This service takes the base64 encoded image as a String parameter.
I want to decode this String into image and upload into server.
@RequestMapping(value="/uploadImage",method = RequestMethod.POST)
public @ResponseBody String uploadImage(@RequestParam("encodedImage") String encodedImage)
{
byte[] imageByte= Base64.decodeBase64(encodedImage);
return null;
}
Convert Image File to Base64 Stringbyte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);
The below code is used to decode the string which is encoded by using base 64 and used to upload image into the server.
This working fine for me..
@RequestMapping(value="/uploadImage2",method = RequestMethod.POST)
public @ResponseBody String uploadImage2(@RequestParam("imageValue") String imageValue,HttpServletRequest request)
{
try
{
//This will decode the String which is encoded by using Base64 class
byte[] imageByte=Base64.decodeBase64(imageValue);
String directory=servletContext.getRealPath("/")+"images/sample.jpg";
new FileOutputStream(directory).write(imageByte);
return "success ";
}
catch(Exception e)
{
return "error = "+e;
}
}
Use Java's Base64.Decoder
to decode the string to a byte array.
If that's not available in your version of Java, you can use the same functionality from the Apache Commons Codec project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With