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

13.5k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On
private String convertToBase64Url(MultipartFile file) {
    String url = "";
    try{
        byte[] bytes = Base64.encodeBase64(file.getBytes());
        String result = new String(bytes);
        url = "data:" + file.getContentType() + ";base64," + result;
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
      return  url;
    }
    
}

try this