Is it possible to do an AJAX form submit without jQuery or IFrames (so just pure JavaScript)? I'm currently sending to a struts fileUploadAction that works. Would the action's code still work with the asynchronous submit, or are there additions required to pick up the async form submit?
I am using struts 1.x and current my form is:
<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
...form elements...
<html:file property="theFile" />
...other elements...
</html:form>
Can this form be submitted, and thus the file uploaded with AJAX?
If I understood you correct, you can use the following code to upload the file async. Modify it as you like
var AjaxFileUploader = function () {
this._file = null;
var self = this;
this.uploadFile = function (uploadUrl, file) {
var xhr = new XMLHttpRequest();
xhr.onprogress = function (e) {
...
};
xhr.onload = function (e) {
...
};
xhr.onerror = function (e) {
...
};
xhr.open("post", uploadUrl, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
};
};
AjaxFileUploader.IsAsyncFileUploadSupported = function () {
return typeof (new XMLHttpRequest().upload) !== 'undefined';
}
if (AjaxFileUploader.IsAsyncFileUploadSupported) {
ajaxFileUploader = new AjaxFileUploader();
$("form").submit(function () {
var uploader = $("#fileUploader")[0];
if (uploader.files.length == 0) {
return;
} else {
ajaxFileUploader.uploadFile(
"/YourUploadUrl",
uploader.files[0]);
}
return false;
});
}
To upload the form use the FormData class, populate it with form values and post it with XHR.
Update: For HTML4 try the following
http://fineuploader.com/ is a ajax file-uploader.
This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With