https://meilishiyan-song.taobao.com/

angularjs实现上传文件动态显示文件列表

html中

<div ng-controler="QAPAnalysisController">


<div class="col-md-12">
<label for="file" class="btn btn-primary">选择文件</label>
<input type="file" id="file" style="display: none" file-upload multiple/><br/>
<div ng-show="files.length > 0">
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>序号</th>
<th>文件名</th>
<th>文件大小</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="file in files">
<td>{{$index+1}}</td>
<td>{{file.name}}</td>
<td>{{file.size/1024/1024|number:2 }} MB</td>
<td><button class="btn btn-danger btn-xs" ng-click="removeFile(file)">删除</button></td>
</tr>
</tbody>
</table>
<button ng-click="uploadFiles()">上传所有文件</button>
</div>
</div>


<br/><br/><br/>

<div class="col-md-2">
<button type="button" class="btn btn-info">解析文件</button>
</div>
</div>

 .js中实现方法如下:

myApp.directive('fileUpload',
['$http',function($http) {
return {
restrict : 'EA',
link : function(scope, el, attrs) {
scope.init = function() {
if (scope.files == null) {
scope.files = new Array();
}
};

scope.pushFile = function(file) {
var flag = true;
scope.init();
if (scope.files.length > 0) {
for (var i = 0; i < scope.files.length; i++) {
if (scope.files[i].name == file.name
&& scope.files[i].size == file.size) {
flag = false;
}
}
}
if (flag) {
scope.files.push(file);
}
};

scope.removeFile = function(file) {
if (scope.files != null
&& scope.files.length > 0) {
for (var i = 0; i < scope.files.length; i++) {
if (scope.files[i].name == file.name
&& scope.files[i].size == file.size) {
scope.files.splice(i, 1);
document
.getElementById("file").value = "";
}
}
}
};

scope.uploadFiles = function() {
var ids = {};
ids.flag = "1";
ids.masterDate = "eps";
$http(
{
method : 'POST',
url : "file/uploadList",
headers : {
'Content-Type' : undefined
},
data : {
flag : "1",
masterDate: "eps",
files : scope.files
},
transformRequest : function(
data) {
var formData = new FormData();
formData.append("flag",angular.toJson(data.flag));
formData.append("masterDate",angular.toJson(data.masterDate));
for (var i = 0; i < data.files.length; i++) {
formData
.append(
"myfiles",
data.files[i]);
}
return formData;
}
})
.success(
function(data, status,
headers, config) {
scope.files = [];
scope.ids = [];
document
.getElementById("file").value = "";
alert(data
+ " files upload success!");
})
.error(
function(data, status,
headers, config) {
alert("failed!");
})
};

el.bind('change', function(event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
scope.pushFile(files[i]);
scope.$apply();
}
});
}
};
} ]);

 

posted @ 2017-03-16 17:35  望梦圆  阅读(1890)  评论(0编辑  收藏  举报
https://meilishiyan-song.taobao.com/