发表于: 2017-07-21 23:35:06
1 841
【JS-TASK-09】怎么将图片上传封装成指令?
1.背景介绍
在js-task-9内,我们需要实现一个将本地图片上传的功能,并且能够进行预览并且将图片的一些属性展示出来。
为了实现这个功能,我们利用所学的angular知识来做一个功能比较简单的图片上传组件。
2.知识剖析
1.基础知识
1.angular指令本质上就是AngularJs扩展具有自定义功能的html元素的途径。
2.内置指令,打包在AngularJs内部的指令,所有内部指令的命名空间 都使用ng作为前缀,所以在写自定义指令的时候,避免用ng作为指令命名的前缀。
3.创建指令的方式有四种,在指令里用 restrict属性控制
2.组件分析
功能:
1.点击按钮上传图片
2.图片能在本地预览
3.上传后能够在本地预览,显示图片信息,显示上传进度
4.点击上传按钮上传到服务器
5.点击删除按钮,删除图片,图片信息一并消失。
3.常见问题
怎么实现上述功能
4.解决方案
指令模板,写在text-ng-template中:
<script type="text/ng-template" id="imgLoad.html">
<div>
<form action="" id="form" enctype="multipart/form-data">
<label for="imgFile">上传:</label>
<input type="file" id="imgFile" multiple="multiple">
<img src="" alt="这里是图片" id="img">
</form>
<table class="table">
<thead>
<tr>
<th>名字</th>
<th>大小</th>
<th>进度</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{name}}</td>
<td>{{size}}</td>
<td><progress id="progress" value='0' max="100"></progress></td>
<td>{{status}}</td>
<td>
<div ng-if="hasImg" class="btn-group">
<button class='btn btn-success' ng-click="upLoad()">上传</button>
<button class="btn btn-danger" ng-click="delete()">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</script>
自定义指令:
myApp.directive('imgUpload', function ($http) {
return {
restrict: 'AEC',
replace: true,
transclude: true,
templateUrl: "imgLoad.html",
link: function (scope, ele, attr) {
scope.imgFile = document.getElementById('imgFile');
scope.img = document.getElementById('img');
var reader = new FileReader();
scope.imgFile.onchange = function () {
reader.readAsDataURL(scope.imgFile.files[0]);
reader.onloadend=function(){
scope.progress=100;
};
scope.$apply(function () {
scope.hasImg = scope.imgFile.files[0];
scope.name = scope.imgFile.files[0].name;
scope.size = (scope.imgFile.files[0].size / 1024).toFixed(2) + 'KB';
scope.delete = function () {
scope.src = ''
scope.img.src = '';
scope.name = '';
scope.status = '';
scope.size = '';
scope.progress='';
scope.hasImg = false
};
})
};
scope.upLoad = function () {
$http({
method: 'post',
url: '/carrots-admin-ajax/a/u/img/task',
headers: {'content-type': undefined},
transformRequest: function () {
var formData = new FormData();
formData.append('file', scope.hasImg);
return formData;
}
}).then(function successCallback(res) {
scope.status = res.data.message;
scope.src = res.data.data.url;
})
}
}
};
});
5.编码实战
6.扩展思考
a.还应该添加一些什么功能
我觉得应该添加一个对于file类型的判定,在上传的不是图片格式的文件时报错
7.参考文献
文件和二进制数据的操作
angular上传获取图片的directive指令
8.更多讨论
怎样优化这个组件,增强组件的复用性,使之可以应用到项目中。
评论