How do I upload image in jQuery function $.ajax()? After that I want to handle it on Servlet by FileUpload library
This is form:
<form id="avatarUploadForm" action="upload" method="post" enctype="multipart/form-data">
<input name="data" id="file" type="file"><br>
<input id="selectFileButton" type="button" value="Select"><br>
<input id="uploadButton" type="button" value="Upload"><br>
</form>
I have the $.ajax() method:
$('#uploadButton').click(function() {
var $form = $('#avatarUploadForm');
var jsonFormData = $form.serializeObject();
$.ajax({
data : { 'file' : jsonFormData },
type : 'POST',
contentType : 'multipart/form-data',
dataType : 'text',
url : 'upload',
success: function(){
alert('uploaded');
}
});
});
And FileUpload method, which must parse my request. It’s in UploadServlet:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List items = upload.parseRequest(request);
How do I convert data from form into HttpServletRequest request?
You can’t do what you asked with ajax.
Here is a very good guide to uploading without refreshing the page, achieving the functionallity of “uploading with ajax”
upload-image-using-hidden-iframe