AJAX file upload/form submit without jquery or iframes?

edwardmlyte picture edwardmlyte · Jul 16, 2012 · Viewed 15.8k times · Source

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?

Answer

Madman picture Madman · Jul 19, 2012

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