怎么将图片上传封装成指令?

</br>

1.背景介绍

在js-task-9内,我们需要实现一个将本地图片上传的功能,并且能够进行预览并且将图片的一些属性展示出来。
为了实现这个功能,我们利用所学的angular知识来做一个功能比较简单的图片上传组件。

2.知识剖析

指令:

1.angular指令本质上就是AngularJs扩展具有自定义功能的html元素的途径。
2.内置指令,打包在AngularJs内部的指令,所有内部指令的命名空间 都使用ng作为前缀,3.所以在写自定义指令的时候,避免用ng作为指令命名的前缀。
4.创建指令的方式有四种,在指令里用 restrict属性控制:E:元素A:属性(这个是比较推荐的方式)C:css类M:注释
5.向指令中传递数据,用template属性

组件功能:

1.点击按钮上传图片
2.图片能在本地预览
3.显示图片信息,显示上传进度
4.点击上传按钮上传到服务器
5.点击删除按钮,删除。
6.上传按钮只能按一次

</br>

3.常见问题

如何实现组件?

</br>

4.解决方案

</br>

5.编码实战

html模板:

<script type="text/ng-template" id="imgLoad.html">
        <div class="box">
            <form id="form" enctype="multipart/form-data">
                <label for="imgFile">上传:</label>
                <label for="imgFile" class="btn btn-primary btn-md" ng-disabled="upDisabled">选择图片</label><span>图片最大为2000000byte(约2MB)</span>
                <input type="file" id="imgFile">
            </form>
            <table class="table">
                <thead>
                <tr>
                    <th>名字</th>
                    <th>大小</th>
                    <th>进度</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody >
                <tr ng-if="hasImg">
                    <td>{{name}}</td>
                    <td>{{size}}</td>
                    <td><progress id="progress" ng-value="progress" max="100"></progress><span>{{progress}}</span></td>
                    <td>{{status}}</td>
                    <td>
                        <div class="btn-group">
                            <button class='btn btn-success' ng-disabled="upDisabled" 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');
            scope.progress='';

            scope.imgFile.onchange = function () {
                if(scope.imgFile.files[0].size>=2000000){
                    alert('图片大小超限~')
                }else{
                    var reader = new FileReader();
                    reader.readAsDataURL(scope.imgFile.files[0]);

                    scope.$apply(function () {
                        scope.hasImg = scope.imgFile.files[0];
                        scope.name = scope.imgFile.files[0].name;
                        scope.size = scope.imgFile.files[0].size > 1024 * 1024 ? (scope.imgFile.files[0].size / 1024 / 1024).toFixed(2) + 'MB' : (scope.imgFile.files[0].size / 1024).toFixed(2) + 'KB';
                    })
                }
            };

            scope.delete = function () {
                scope.img.src = '';
                scope.hasImg = false;
                scope.upDisabled = false;
            };

            scope.upLoad = function () {
                $http({
                    method: 'post',
                    url: '/carrots-admin-ajax/a/u/img/task',
                    headers: {'content-type': undefined},
                    uploadEventHandlers:{
                        progress: function(e) {
                            if (e.lengthComputable) {
                                scope.progress = Math.round(e.loaded * 100 / e.total);
                            }
                        }
                    },
                    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;
                    scope.upDisabled = true;
                },function errorCallback(res) {
                    scope.status = res.data.message;
                    scope.upDisabled = true;
                })
            }
        }
    };
});

</br>

6.扩展思考

还应该添加一些什么功能?

还应该添加上传的文件是否是图片的验证。

</br>

7.参考文献

$http服务
FileReader : EventTarget
文件和二进制数据的操作

</br>

8.更多讨论

1.图片上传的document.getElementById('file').files为何是一个数组?

图片上传可以一次上传多个文件,故files对象是一个数组。

2.如何同时上传多个文件?

input中添加multiple="multiple"属性,则可一次性选择多个文件,document.getElementById('file').files中有多个file文件.

3.当我们再次选择文件上传时,files数组会发生什么?

当我们再次选择文件上传时,此files数组会被覆盖并非添加文件到此数组中。

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、背景介绍 如果我们想实现图片上传功能,其中需要包含以下功能*点击按钮上传图片*图片能在本地预览*显示图片信息,...
    8778188a234f阅读 452评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,256评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,539评论 25 709
  • 今日诸事不宜 -封--我--床- Over 感觉渣渣外卖的麻辣香锅还没我做的好吃
    李汪汪汪侠阅读 136评论 0 0
  • 下了班,开车回家。 突然,想到三年前的今天和几十个兄弟姐妹宣誓的场景。 噢,是个值得纪念的日子! 附上,前几天,一...
    L_ea90阅读 225评论 0 0