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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With