Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload encoded base64 image to the server using spring

Tags:

spring

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;
}
like image 243
srihari Avatar asked Jun 14 '14 09:06

srihari


People also ask

How can I convert an image into Base64 string using Java?

Convert Image File to Base64 Stringbyte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);


2 Answers

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;
        }

    }
like image 183
srihari Avatar answered Oct 22 '22 20:10

srihari


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.

like image 3
Robby Cornelissen Avatar answered Oct 22 '22 21:10

Robby Cornelissen