On server side I have spring MVC (JAVA) project which accepts multipart/form-data with MultipartFile
@RequestMapping(value = { "/uploadImg/**" }, method = RequestMethod.POST)
public void uploadImg(Model model, HttpServletRequest request,HttpServletResponse response,MultipartFile file )
{
String originalFileName = file.getOriginalFilename();
//some cases on based on file name and storing the file into the server
}
Previously, I am using <fomr>
with <file>
to upload the file. But now I have a image data in base64 format and wanted to upload using AJAX to same request mapping.
I come across this Upload base64 image with Ajax and plenty of such solutions. But all are uploading file data only but in my case I want to upload image with its data and name, as on server side some logic is written based on file name.
One option might be that, sending image data in parameter and file name in another parameter but I don’t have access (or rather I cannot change) the server side code to do this.
So, using AJAX how can I upload base64 image data along with file name ?
2
Answers
I tested the following code with a PHP server. I don’t have access to a Spring MVC server, but the JS code should be the same for both. The code is mostly based on this article: https://ourcodeworld.com/articles/read/322/how-to-convert-a-base64-image-into-a-image-file-and-upload-it-with-an-asynchronous-form-using-jquery
The best would be to change whatever generates this base64 version so it returns a Blob instead directly.
In the absence of such an option, you can still convert that base64 string into a Blob yourself.
Once you have the Blob, you’ll be able to post it to your server using either
XMLHttpRequest
orfetch
, just like an html<form>
thanks to the FormData API.