Manual implementation
You can add multiple upload buttons on the page by adding elements to a% container. Example:
$('#container').append('<input type="file" />');
Then at the time of sending you put everything into an object of type div
. Example:
var formData = new FormData();
formData.append('imagem', file, file.name);
Finally send everything via AJAX using FormData
. Example:
var xhr = new XMLHttpRequest();
...
xhr.send(formData);
See a complete example:
$('#adicionar').on('click', function() {
$('#container').append('<input type="file" />');
});
$('#enviar').on('click', function() {
var formData = new FormData();
$('#container input').each(function() {
formData.append('imagens[]', this, this.name);
});
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadServlet', true);
xhr.onload = function() {
if (xhr.status === 200) {
alert('Sucesso!');
} else {
alert('Erro!');
}
};
xhr.send(formData);
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="adicionar">+</button> <button id="enviar">enviar</button>
<div id="container"></div>
Using a plugin
The code above is very simple and works in most modern browsers.
However, if you want to avoid getting into the many implementation details that this could entail in a true system that goes from formatting to support for older browsers, I suggest using a plugin for this.
One plugin I've used successfully in the past was the Blueimp jQuery File Upload .
You can find several examples in the documentation , although in practice this might even hinder a little because it has so many ways to use that you end up spending a lot of time learning about the plugin.
However, a very simple use might look something like this:
$('#fileupload').fileupload({
dataType: 'json',
add: function (e, data) {
data.context = $('<button/>').text('Upload')
.appendTo(document.body)
.click(function () {
data.context = $('<p/>').text('Uploading...').replaceAll($(this));
data.submit();
});
},
done: function (e, data) {
data.context.text('Upload finished.');
}
});
Servlet
To get uploaded to your servlet, I suggest using the Apache Commmons FileUpload library.
Understand that from the server's point of view, uploads are complex to manage. The library documentation gives numerous examples of the control you may have.
A simpler case would look like this:
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : itens) {
if (!item.isFormField()) {
String fileName = item.getName();
String contentType = item.getContentType();
File uploadedFile = new File(...);
item.write(uploadedFile);
} else {
//campos normais
String campo = item.getFieldName();
String valor = item.getString();
}
}
Note that you can not access the other fields using XMLHttpRequest
and related methods, since the body of a request where uploads occur is different and the server will not decode the fields in the same way as on a normal request.
So, as in the example above, you should check the other fields of the request in the same list of items where the files are. When it is a normal field, request.getParameter()
will be true.
For a more complete description, see this SO response .