繁体   English   中英

在 Angular JS 中使用进度条上传文件

[英]File upload with progress bar in Angular JS

有没有人可以帮助我在上传文件时如何放置进度条以指示用户该文件仍在上传? 对不起,我对这个还是个新手。 我阅读了很多关于此的内容,但仍然让我感到困惑。 先感谢您!

这是我将提交文件的 html:

     <form class="form-group" ng-submit="addX()">
        <div class="col-lg-4">
            <input id="file" type="file" name="file" class="file btn btn-default"  data-show-preview="false"><br>
            <input id="submit" class="btn btn-primary" type="submit" name="submit" value="Upload" /><br/><br/>
        </div>
     </form>

这是我的 js,它将我连接到我的 python 文件:

 $scope.addX = function() {
         var f = document.getElementById('file').files[0]; console.log(f);
         var formData = new FormData();
         formData.append('file', f); console.log(formData);
           $http({method: 'POST', url: 'http://x.x.x./',
                           data: formData,
                           headers: {'Content-Type': undefined},
                           transformRequest: angular.identity})
                  .success(function(data, status, headers, config) {
                            if (data.success) {

                                console.log('import success!');

                            }
                        })
                        .error(function(data, status, headers, config) {
                        });
                // }
            };

不幸的是,目前这似乎不可能。 您可以关注此线程https://github.com/angular/angular.js/issues/1934 ,该线程要求访问 xhr 请求,您也需要该线程更新进度。 目前您需要自己使用 XHR2 对象。 像这样的东西

var fd = new FormData();
fd.append("uploadedFile", file);

xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", uploadProgress, false);

xhr.addEventListener("readystatechange", function (e) {
// upload completed
if (this.readyState === 4) {

// do whats needed
}

xhr = null;
}
});

xhr.addEventListener("error", function (e) {
 callback(e);
});
//xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", url);

// send the form data to the server
xhr.send(fd);

解决此问题的另一种选择是在服务器端处理它,以防您确实可以控制服务。

对于那些在 $http 中搜索选项的人,以下内容会有所帮助。 有一种方法可以通过监听事件 'uploadEventHandlers' 来获取文件上传进度

https://stackoverflow.com/a/41930083/6282758

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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