Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX file upload/form submit without jquery or iframes?

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?

like image 625
edwardmlyte Avatar asked Jul 16 '12 14:07

edwardmlyte


2 Answers

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://www.albanx.com/?pid=5&subid=21
  • Asynchronous file upload (AJAX file upload) using jsp and javascript
like image 126
Madman Avatar answered Nov 11 '22 16:11

Madman


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.

like image 30
paulslater19 Avatar answered Nov 11 '22 16:11

paulslater19