AJAX file upload/form submit without jquery or iframes?

前端 未结 3 1166
野趣味
野趣味 2020-12-31 19:39

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 actio

3条回答
  •  借酒劲吻你
    2020-12-31 20:16

    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

提交回复
热议问题