Hi i am uploading a file using <input type="file">
in spring mvc. I submit form on change event of file and show uploaded process. But file content not uploaded and get null on server. If i upload on click of submit button every thing works fine. This is my code:
Html File:
<form:form method="POST" modelAttribute="book" id="saveBook"
name="saveBook" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Book :</td>
<td> </td>
<td>
<input type="file" name="file" id="file" class="edit_form" onchange="return upload('<c:url value='/bookstore/librery/uploadBook' />', 'saveBook', this);" />
<form:errors path="file" />
</td>
</tr>
</table>
</form:form>
Jquery Code:
function upload(requestUrl, formId, clickedObj) {
if (clickedObj && eval(clickedObj) && clickedObj != null && clickedObj != undefined) {
clickedObj.disabled = true;
}
var formData = new FormData(document.getElementById(formId));
$.ajax({
'url': requestUrl,
'type': 'POST',
'data': formData,
'cache': false,
'contentType': false,
'processData': false,
success: function (data) {
$("#tempLoc").val(data.tempLoc);
$("#bookPreview").attr("src", "data:image/png;base64," + data.image);
$("#image").val(data.image);
clickedObj.disabled = false;
},
error: function (xhr, status, err) {
clickedObj.disabled = false;
var tempErrorHTML = getAjaxRequestErrorMsg(xhr);
alert(tempErrorHTML);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress
alert('percentComplete = ' + percentComplete + '%');
}
}, false);
return xhr;
},
}, 'json');
}
If i call upload function on click of submit button every thing works fine. I think form is submitted before file uploaded but don't know how to make things correct.
I can't use submit function because I need to show upload progressbar. Please help.
Thanks In Advance.