XHR Level2 with jQuery for file upload

前端 未结 2 2021
不思量自难忘°
不思量自难忘° 2020-12-31 23:06

How can I access the raw XHR object from jQuery Ajax? The thing is, the new XMLHttpRequest Level 2 specification provides a sub-property of XHR called upload but apparently

2条回答
  •  礼貌的吻别
    2020-12-31 23:47

    A little modification to DannYOs answer. I made a jQuery plugin that you can call on a file input to make it simpler. You just pass it your upload script, then your success function and then your progress function.

    $.fn.upload = function(remote,successFn,progressFn) {
        return this.each(function() {
    
            var formData = new FormData();
            formData.append($(this).attr("name"), $(this)[0].files[0]);
    
            $.ajax({
                url: remote,
                type: 'POST',
                xhr: function() {
                    myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload && progressFn){
                        myXhr.upload.addEventListener('progress',progressFn, false);
                    }
                    return myXhr;
                },
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                complete : function(res) {
                    if(successFn) successFn(res);
                }
            });
        });
    }
    

    Usage

    $(".myFile").upload("upload.php",function(res) {
        console.log("done",res);
    },function(progress) {
        console.log("progress", progress);
    });
    

提交回复
热议问题