I'm creating a JSP/Servlet web application and I'd like to upload a file to a Servlet via Ajax. How would I go about doing this? I'm using jQuery.
I've done so far:
<form class="upload-box">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error" />
<input type="submit" id="upload-button" value="upload" />
</form>
With this jQuery:
$(document).on("#upload-button", "click", function() {
$.ajax({
type: "POST",
url: "/Upload",
async: true,
data: $(".upload-box").serialize(),
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
$("#upload-error").html("Couldn't upload file");
}
});
});
However, it doesn't appear to send the file contents.
@Monsif's code works well if the form has only file type inputs, if the there are some other inputs other then file type, then they get lost. So, instead of copying each form data and appending them to FormData object, the original form itself can be given to the constructor.
Regarding the @Monsif's code and https://www.new-bamboo.co.uk/blog/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata/ post, I came out with the following code which worked for me. I hope it helps someone else.
The html code can be something like following:
This code works for me.
Used commons io.jar & commons file upload.jar and the jQuery form plugin
To the point, as of the current
XMLHttpRequest
version 1 as used by jQuery, it is not possible to upload files using JavaScript throughXMLHttpRequest
. The common workaround is to let JavaScript create a hidden<iframe>
and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing such as jQuery Form plugin (example here).Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JS disabled (as you have now...), like below:
Then it's with help of jQuery Form plugin just a matter of
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How to upload files to server using JSP/Servlet?
You'll only need an additional check in the servlet if the
X-Requested-With
header equals toXMLHttpRequest
or not, so that you know how what kind of response to return for the case that the client has JS disabled (as of now, it are mostly the older mobile browsers which have JS disabled).Note that the relatively new
XMLHttpRequest
version 2 is capable of sending a selected file using the newFile
andFormData
APIs. See also HTML5 File Upload to Java Servlet and sending a file as multipart through xmlHttpRequest.This code works fine for me :