[FIXED] 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) {
    return "";

How can I get the data URI of the image?


After much searching I found the answer here.

StringBuilder sb = new StringBuilder();
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.

Answered By – Jaydo

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published