I was trying to upload file in my web application using ajax and servlets. My ajax code is something like this :
<script>
var client = new XMLHttpRequest();
function upload2() {
alert("in upload");
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "fileupload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function () {
if (client.readyState == 4 && client.status == 200) {
alert(client.statusText);
}
}
</script>
My form is something like this :
<input type="file" name="uploadfile" id="uploadfile"/>
<input type="button" value="upload" name="upload" onclick="upload2()"/>
And my servlet that is being called in function is :
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
for (FileItem fi : upload.parseRequest(request)) {
if (fi.isFormField()) {
continue;
}
System.out.println("filename: " + fi.getName());
InputStream is = fi.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\Files\\" + fi.getName());
int x = is.read();
while (x >= 0) {
fos.write((byte) x);
x = is.read();
System.out.println("reading");
}
}
But am getting an exception with this code :
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
The main problem I think is how to use the form data that has been formed by appending the file in my Servlet part.
My question is what is the cause of this exception?
Second question is how to modify my code so that I can upload multiple files at a time? Please help.