最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX file uploadform submit without jquery or iframes? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jul 17, 2012 at 7:53 edwardmlyte asked Jul 16, 2012 at 14:32 edwardmlyteedwardmlyte 16.6k23 gold badges61 silver badges83 bronze badges 9
  • 1 yes you can do it by javascript – NullPoiиteя Commented Jul 16, 2012 at 14:36
  • Not all browsers support it without the iframe. – epascarello Commented Jul 16, 2012 at 15:01
  • I've seen that I need to either create a XMLHttpRequest or an ActiveXObject for browser compatibility, any chance of an example of the JavaScript? – edwardmlyte Commented Jul 16, 2012 at 15:14
  • 1 @edwardmlyte, just being curious, while jquery is the most popular and standard library for cross browser implementation of JS, why you need pure javascript solution that might not be compatible everywhere? – Furqan Hameedi Commented Jul 19, 2012 at 6:56
  • 2 Good question. Simply put, company policy. Why bring in an external library if you can manage without (regardless of ease). – edwardmlyte Commented Jul 19, 2012 at 7:34
 |  Show 4 more comments

4 Answers 4

Reset to default 14 +50

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

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";
发布评论

评论列表(0)

  1. 暂无评论