简体   繁体   中英

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?

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.

The up-to-date (march 2022), pure js solution, can be found in here . Summary:

You can use fetch optionally with await-try-catch

 let photo = document.getElementById("image-file").files[0]; let formData = new FormData(); formData.append("photo", photo); fetch('/upload/image', {method: "POST", body: formData});

No need to add jquery or any other third party library, just add IPerfect JS library and you are good to go.

IP_uploadFile(URL,responseType,this[object],[dynamicFunctionForResponse])

if user select responseType as 'html' then dynamicFunctionForResponse will get response in HTML format. In below example you will get 'done' response in alert.

HTML

    <script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js"></script>


    <script language='javascript'>
    function testResponse(data){
    alert(data)
    }
    </script>

Body

    <form method="POST" enctype="multipart/form-data"  onsubmit="IP_uploadFile('testupload.php','html',this,testResponse); return false;">
        <input type="file" name="file1">
        <input type="submit" name="submit1" value="Click here">
    </form>

PHP: testupload.php

    move_uploaded_file($_FILES['file1']['tmp_name'], realpath("./")."/upload/".$_FILES["file1"]["name"]);
    echo "done";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM