I have a problem with the code, the servlet is not called. Only works if I put action="FileUploader" in form. Is there a mistake? Do you have any other way to do it? What I need: An array of images, where images are received in a single multiple / form data field (that is, all images received at one time) that is passed to the servlet, without redirecting the page. Thank you in advance.
<form id="form1">
<label for="sampleText">Please enter a text</label>
<input id="sampleText" name="sampleText" type="text" /> <br/>
<label for="sampleFile">Please select a file
<input id="sampleFile" name="sampleFile" type="file" /> <br/>
<input id="uploadBtn" type="button" value="Ajax Submit" onClick="performAjaxSubmit();"></input>
</form>
<script type="text/javascript">
function performAjaxSubmit() {
var sampleText = document.getElementById("sampleText").value;
var sampleFile = document.getElementById("sampleFile").files[0];
var formdata = new FormData();
formdata.append("sampleText", sampleText);
formdata.append("sampleFile", sampleFile);
var xhr = new XMLHttpRequest();
xhr.open("POST","FileUploader", true);
xhr.send(formdata);
xhr.onload = function(e) {
if (this.status == 200) {
alert(this.responseText);
}
};
}
</script>
public class FileUploader extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String ajaxUpdateResult = "";
try {
List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
ajaxUpdateResult += "Field " + item.getFieldName() +
" with value: " + item.getString() + " is successfully read\n\r";
} else {
String fileName = item.getName();
InputStream content = item.getInputStream();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
// Do whatever with the content InputStream.
System.out.println(Streams.asString(content));
ajaxUpdateResult += "File " + fileName + " is successfully uploaded\n\r";
}
}
} catch (FileUploadException e) {
throw new ServletException("Parsing file upload failed.", e);
}
response.getWriter().print(ajaxUpdateResult);
}
}