I got a requirement where i need submit a form which contains file input asynchronously using ajax. Following is the code i written. but it is giving me error.
Input.jsp:
<script>
function fileUpload()
{
var formData = $('#myform').serialize();
$.ajax({
type: "POST",
url: "second.jsp",
async: true,
data: formData,
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
alert("Failed to upload file");
}
});
}
</script>
<form name="myform" id="myform" action="#" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Slide Name :</td>
<td><input type="text" name="filename"></td>
</tr>
<tr>
<td>Video File :</td>
<td><input type="file" name="filecontent"></td>
</tr>
<tr>
<td>Some input :</td>
<td><input type="radio" name="myinput" value="y" >Yes <input type="radio" name="myinput" value="n">No</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="Submit" onclick="fileUpload()"></td>
</tr>
</table>
</div>
</form>
second.jsp
<body>
<%
String fileLocation="D://";
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (item.isFormField()) {
String fieldName = item.getFieldName();
String fieldValue = item.getString();
} else {
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
String name = new File(item.getName()).getName();
item.write(
new File(fileLocation + File.separator + name));
}
}
System.out.println("File Uploaded Successfully");
} catch (Exception ex) {
System.out.println("File Upload Failed due to " + ex);
}
}
%>
</body>
Error i am getting is: i am getting following error in console
File Upload Failed due to org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found