angular-file-upload封装为指令+图片尺寸限制

前端之家收集整理的这篇文章主要介绍了angular-file-upload封装为指令+图片尺寸限制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

不了解angular-file-upload基础使用

请先参考http://blog.csdn.net/lai_xu/article/details/49535847 博客地址

下文如果有更好的建议请多多评论

1. directive.js中的指令编写

/*
    上传插件
*/
app.directive('myUpload',function (FileUploader) {
    var helper = {
        getType: function (name) {
            return '|' + name.slice(name.lastIndexOf('.') + 1) + '|';
        },/*
            type 类型
            closeMsg  true 关闭提示
        */
        isImage: function (type,closeMsg) {
            if ('|jpg|png|jpeg|bmp|gif|'.indexOf(type.toLowerCase()) !== -1) {
                return true;
            } else {
                if (!closeMsg) {
                    layer.alert("请确定文件格式为|jpg|png|jpeg|bmp|gif|",{ icon: 7 });
                    return false;
                }
            }
        },isDoc: function (type,closeMsg) {
            if ('|doc|docx|txt|'.indexOf(type.toLowerCase()) !== -1) {
                return true;
            } else {
                if (!closeMsg) {
                    layer.alert("请确定文件格式为|doc|docx|txt|",isVideo: function (type,closeMsg) {
            if ('|rm|rmvb|avi|mp4|3gp|'.indexOf(type.toLowerCase()) !== -1) {
                return true;
            } else {
                if (!closeMsg) {
                    layer.alert("请确定文件格式为|rm|rmvb|avi|mp4|3gp|",isMp3: function (type,closeMsg) {
            if ('|mp3|'.indexOf(type.toLowerCase()) !== -1) {
                return true;
            } else {
                if (!closeMsg) {
                    layer.alert("请确定文件格式为|mp3|",isZip: function (type,closeMsg) {
            if ('|zip|rar|'.indexOf(type.toLowerCase()) !== -1) {
                return true;
            } else {
                if (!closeMsg) {
                    layer.alert("请确定文件格式为|zip|rar|",//检查尺寸是否符合规范
        uploadImgCheckedPx: function (f,w,h,msg,callback) {
            if (w && h) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    //判断图片尺寸
                    var img = null;
                    img = document.createElement("img");
                    document.body.appendChild(img);
                    img.style.visibility = "hidden";
                    img.src = this.result;
                    var imgwidth = img.naturalWidth;
                    var imgheight = img.naturalHeight;
                    if (imgwidth != w || imgheight != h) {
                        document.body.removeChild(img);
                        if (msg) {
                            msg += ">";
                        } else {
                            msg = "";
                        }
                        //询问框
                        layer.confirm(msg + "尺寸建议" + w + "x" + h + ",确定上传吗?",{
                            btn: ['确定','取消'],cancel: function () {
                                callback && callback(false);
                            }
                        },function (index) {
                            layer.close(index);
                            callback && callback(true);
                        },function () {
                            callback && callback(false);
                        });
                    } else {
                        callback && callback(true);
                    }
                }
                if (f)
                    reader.readAsDataURL(f);
            } else {
                callback && callback(true);
            }
        }
    };
    return {
        restrict: 'E',replace: true,scope: {
            filters: '@filters',response: '=response',size: '=size',callback: '@callback',width: '@width',height: '@height',msg: '@msg'
        },template: '<input type="file"  nv-file-select="" uploader="uploader" filters="{{filters}}" />',link: function (scope,element,attributes) {
            element.bind("change",function (changeEvent) {
                scope.$apply(function () {
                    scope.selectedFile = changeEvent.target.files[0];
                    var type = helper.getType(scope.selectedFile.name);
                    if (helper.isImage(type,true)) {
                        helper.uploadImgCheckedPx(scope.selectedFile,scope.width,scope.height,scope.msg,function (state) {
                            if (state)
                                scope.uploader.uploadAll();
                            else
                                scope.uploader.clearQueue();
                        });
                    } else {
                        scope.uploader.uploadAll();
                    }
                });
            });
        },controller: function ($scope) {
            var uploader = $scope.uploader = new FileUploader({
                url: '/Handler/Upload.ashx',autoUpload: false,//自动上传
                removeAfterUpload: true,//文件上传成功之后从队列移除,默认是false
                queueLimit: 1// 最大上传文件数量
            });
            //文件限制提示语
            var showMsg = function (itemSize,maxSize) {
                if (itemSize / 1024 >= maxSize) {
                    layer.alert("文件大小必须小于" + (maxSize).toFixed(0) + "KB",{ icon: 7 });
                    return false;
                }
                $scope.size = itemSize;
                return true;
            }
            // FILTERS
            uploader.filters.push({
                name: 'imageFilter',fn: function (item /*{File|FileLikeObject}*/,options) {
                    if (!showMsg(item.size,4096)) {
                        return false;
                    }
                    var type = helper.getType(item.name);
                    return helper.isImage(type) && this.queue.length < 5;
                }
            },{
                name: 'docFilter',3072)) {
                        return false;
                    }
                    var type = helper.getType(item.name);
                    return helper.isDoc(type);
                }
            },{
                name: 'videoFilter',204800)) {
                        return false;
                    }
                    var type = helper.getType(item.name);
                    return helper.isVideo(type);
                }
            },{
                name: 'mp3Filter',20480)) {
                        return false;
                    }
                    var type = helper.getType(item.name);
                    return helper.isMp3(type);
                }
            },{
                name: 'zipFilter',20480)) {
                        return false;
                    }
                    var type = helper.getType(item.name);
                    return helper.isZip(type);
                }
            });
            // CALLBACKS

            uploader.onWhenAddingFileFailed = function (item,filter,options) {
                console.info('onWhenAddingFileFailed',item,options);
            };
            uploader.onAfterAddingFile = function (fileItem) {
                console.info('onAfterAddingFile',fileItem);
            };
            uploader.onAfterAddingAll = function (addedFileItems) {
                console.info('onAfterAddingAll',addedFileItems);
            };
            uploader.onBeforeUploadItem = function (item) {
                console.info('onBeforeUploadItem',item);
            };
            uploader.onProgressItem = function (fileItem,progress) {
                console.info('onProgressItem',fileItem,progress);
            };
            uploader.onProgressAll = function (progress) {
                console.info('onProgressAll',progress);
            };
            uploader.onSuccessItem = function (fileItem,response,status,headers) {
                console.info('onSuccessItem',headers);
                if (response.indexOf("error") == -1) {
                    $scope.response = response;
                    if ($scope.callback) {
                        $scope.$emit($scope.callback,response);
                    }
                }
                else {
                    layer.alert(response,{ icon: 2 });
                }
            };
            uploader.onErrorItem = function (fileItem,headers) {
                console.info('onErrorItem',headers);
            };
            uploader.onCancelItem = function (fileItem,headers) {
                console.info('onCancelItem',headers);
            };
            uploader.onCompleteItem = function (fileItem,headers) {
                console.info('onCompleteItem',headers);
            };
            uploader.onCompleteAll = function () {
                console.info('onCompleteAll');
            };
        }
    };
});

2.如何使用

<!--
filters  代表 你使用指令中的哪个过滤器 例如 imageFilter docFilter 具体看 directive.js中的 filters
msg  提示语
width height  图片的限制尺寸
response 回掉属性 上传成功后会 给你的 $scope.resUrl赋值
callback 回掉方法 上传成功后会 触发你的 callback 方法 从而实现多图上传
size  回掉属性 上传成功后会 给你的 $scope.fileSize赋值 单位b字节
--> 
<my-upload filters="imageFilter" msg="单张图片" width="690" height="350" response="resUrl" callback=""></my-upload>
 <my-upload filters="imageFilter" msg="多张图片" width="690" height="350" response="" callback="addScenicLongPicEvent"></my-upload>
 <my-upload filters="mp3Filter" response="currentItem.VoiceUrl" size="fileSize"></my-upload>

3.controller中回掉方法

//多图添加事件 对比2中 上传图片callback方法
    $scope.$on('addScenicLongPicEvent',function (event,res) {
        $scope.currentScenicLongPic.push(res);
    });

4.后台上传代码

/// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var file = context.Request.Files[0];
                var debugState = System.Configuration.ConfigurationManager.AppSettings["DebugState"];
                var path = file.FileName.Substring(file.FileName.LastIndexOf("."));
                var name = "qhLjlx/" + path + "/" + ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000) + new Random().Next(10,99); //时间戳
                name += path;  //获取文件名称 
                var resUrl = "";
                //aliyun upload
                if (LjlxUpdate.UpdateAL(name,file.InputStream,out resUrl,debugState == "true"))
                    context.Response.Write(resUrl);
                else
                    context.Response.Write("error|服务器端错误远程阿里云上传失败!");
            }
            catch (Exception ex)
            {
                context.Response.Write("error|" + ex.Message);
            }
            return;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
原文链接:https://www.f2er.com/angularjs/147820.html

猜你在找的Angularjs相关文章