在文件上传过程中为进度提供角度$http $watch
angular $http $watch for progress during file uploading
我有一个这样的函数:
$scope.fileUpload = function (files) {
angular.forEach(files, function () {
var fd = new FormData();
fd.append('files[]', files[0]);
$http.post('/my-url', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined}
}).then(function (data) {
console.log(data);
});
});
};
和模板:
<input type="file"
name="files[]"
id="fileUploaderButton_contentFormFiles"
onchange="angular.element(this).scope().fileUpload(files)"
multiple>
<div class="progress" id="fileUploaderProgressbar_contentFormFiles">
<div class="progress-bar progress-bar-striped active"
role="progressbar"
aria-valuenow="{{progress}}"
aria-valuemin="0"
aria-valuemax="100"
style="min-width: 2em; width: {{progress}}%">
<span>{{progress}}%</span>
</div>
</div>
如何$watch上传文件的传输值(字节),以便我可以在请求期间更新进度条中的 {{progress}}$http(使用本机角度功能)?提前谢谢。
不是你想要的答案,但你的方法错了
您应该使用 ng-file-upload,这是标准的角度方法,并支持上传进度跟踪
非常感谢
大家的建议。我的解决方案是使用 XMLHttpRequest 而不是$http服务:
$scope.fileUpload = function (files) {
angular.forEach(files, function () {
var fd = new FormData();
fd.append('files[]', files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (event) {
$scope.progress = Math.floor((event.loaded / event.total) * 100);
console.log(event.loaded + ' / ' + event.total);
}
xhr.open("POST", '/my-url', true);
xhr.send(fd);
});
};
您可以使用 ng-file-upload 指令。它支持非HTML5浏览器的拖放,文件进度/中止和文件上传。
.HTML:
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
.JS:
//make sure you inject angularfileupload
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
相关文章:
- Meteor如何接收HTTP请求
- 在我的情况下,如何进行http请求
- //而不是在src=“”上使用http://"属性
- 我无法使用angularJs($http)访问服务器
- AJAX简单错误.XMLHttpRequest无法加载http://localhost/mpl/getPage.php.
- 如何将PHP get查询转换为Meteor's HTTP.get()
- 角度异步http自动完成
- 什么's本地node.js服务器和python简单http服务器之间的区别
- 角度http服务器页面刷新404s
- http.listen()在运行时接受终端命令
- IIS动态HTTP响应标头
- spring和angularJS(我得到了类似HTTP状态404的错误)
- 存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应
- Typescript angularjs$http获取响应类型(避免使用<any>)
- 如何从HTTP上下文对象中获取Post数据
- angularjs$watch获取已更改数组项的索引
- 使用插件收听Firefox标签的http请求
- "访问控制允许起源”;通过javascript从http页面调用同一网站的httpsurl时出现问题
- 使用 $watch 在属性更改时执行$http调用的角度服务
- 在文件上传过程中为进度提供角度$http $watch