$http upload file progress in AngularJS

后端 未结 6 1687
南笙
南笙 2020-12-04 22:19

How can I get a \'progress\' event from my AngularJS $http POST request that is uploading an image? Is it possible to do this client-side, or do I need the server to report

6条回答
  •  [愿得一人]
    2020-12-04 22:58

    Here is another solution:

    window.XMLHttpRequest = (function (orig) {
        if (orig) {
            var intercept = [],
                result = function () {
                var r = new orig();
    
                if (r.upload) {
                    $(r).on(
                        'abort error load loadend loadstart progress',
                        function (e) {
                            $(document).trigger('upload.XHR', e);
                        }
                    );
                }
    
                if (intercept.length) {
                    intercept[0].push({
                        request:r
                    });
                }
    
                return r;
            };
    
            result.grab = function (f) {
                intercept.unshift([]);
                f();
                return intercept.shift();
            };
    
            return result;
        }
    
        return function () {
            try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
            try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
            try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
            throw new Error("This browser does not support XMLHttpRequest.");
        };
    }(window.XMLHttpRequest));
    

    Notes:

    • AngularJS currently stores a reference to window.XMLHttpRequest as private XHR variable, then uses it like this: new XHR(). I doubt this will ever change, so the shim-like code above should work just fine.

    • Mozilla has some extensions: XMLHttpRequest accepts optional arguments. The code above does not handle this, but AngularJS does not use these extensions anyway.

    • One of possible uses (if you want to show all current requests, and maybe implement some "Cancel" button):

    $(document).on('upload.XHR', function (_e, e) {
       switch (e.type) {
           // do your thing here
       }
    });
    
    • Another possible use:
    var list = window.XMLHttpRequest.grab(function () {
        // start one or more $http requests here, or put some code
        // here that indirectly (but synchronously) starts requests
        $http.get(...);
        couchDoc.save();
        couchDoc.attach(blob, 'filename.ext');
        // etc
    });
    
    list[0].request.upload.addEventListener(...);
    
    • Or, you can combine both approaches with some modifications to the code above.

提交回复
热议问题