How to convert a MultiPartFile (image) to a data URI?

Jaydo picture Jaydo · Jun 17, 2015 · Viewed 9.3k times · Source

On my site I am uploading an image and need to return the data URI of that image but I cannot work out how to do so (it must be server side).

I have tried the following code but it seems to encode the name of the file.

@RequestMapping(value="/path/toDataURL", method=RequestMethod.POST, headers = "content-type=multipart/form-data")
public @ResponseBody String uploadMultipart(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile multiPart) {
    try {
        return "data:image/png;base64," + Base64.encodeBase64(multiPart.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

How can I get the data URI of the image?

Answer

Jaydo picture Jaydo · Jun 17, 2015

After much searching I found the answer here.

StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
return sb.toString();

The trick is to StringUtils.newStringUtf8(...).
Other methods I tried returned a string 10 characters long or an improperly formed data URI.