I am uploading an image from the desktop, and converting this image into base code in javascript. After that I want to send this image base code to spring controller with the multipart request. But I am not using Form.
HTML
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL()">
JAVA SCRIPT
window.photoCakeUrl = '<c:url value="/media/image/upload"/>';
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
var photoCake = srcData;
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
var ajax1 = $.ajax({
type: 'POST',
url: photoCakeUrl,
processData: false, // important
contentType: false, // important
dataType: 'json',
data: {photoCak: photoCake}
});
});
},
fileReader.readAsDataURL(fileToLoad);
}
}
SPRING CONTROLLER:
@RequestMapping(value = "/media/image/upload", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> productPictureUploadnew(MultipartHttpServletRequest request, HttpServletResponse response) {
Map<String, String> resp = new HashMap<>();
String photoCake = request.getParameter("photoCak");
System.out.println("photoCake " + photoCake);
return resp;
}
But when I am generating AJAX call then 500 error will comes. If i am using simply
public Map<String, String> productPictureUploadnew(HttpServletRequest
request, HttpServletResponse response)
Then it works. Mean when I am using MultipartHttpServletRequest place of HttpServletRequest request then it is not works.
I got solution, We can use formData in javascript without using form in any JSP to send MultipartHttpServletRequest.
Controller:
Thanks you, I hope this is help full for you guys.