Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 831
Jaydo Avatar asked Jun 17 '15 04:06

Jaydo


1 Answers

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.

like image 184
Jaydo Avatar answered Oct 31 '22 04:10

Jaydo