首页 > 代码库 > 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|", { icon: 7 }); return false; } } }, 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|", { icon: 7 }); return false; } } }, isMp3: function (type, closeMsg) { if (‘|mp3|‘.indexOf(type.toLowerCase()) !== -1) { return true; } else { if (!closeMsg) { layer.alert("请确定文件格式为|mp3|", { icon: 7 }); return false; } } }, isZip: function (type, closeMsg) { if (‘|zip|rar|‘.indexOf(type.toLowerCase()) !== -1) { return true; } else { if (!closeMsg) { layer.alert("请确定文件格式为|zip|rar|", { icon: 7 }); return false; } } }, //检查尺寸是否符合规范 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‘, fn: function (item /*{File|FileLikeObject}*/, options) { if (!showMsg(item.size, 3072)) { return false; } var type = helper.getType(item.name); return helper.isDoc(type); } }, { name: ‘videoFilter‘, fn: function (item /*{File|FileLikeObject}*/, options) { if (!showMsg(item.size, 204800)) { return false; } var type = helper.getType(item.name); return helper.isVideo(type); } }, { name: ‘mp3Filter‘, fn: function (item /*{File|FileLikeObject}*/, options) { if (!showMsg(item.size, 20480)) { return false; } var type = helper.getType(item.name); return helper.isMp3(type); } }, { name: ‘zipFilter‘, fn: function (item /*{File|FileLikeObject}*/, options) { if (!showMsg(item.size, 20480)) { return false; } var type = helper.getType(item.name); return helper.isZip(type); } }); // CALLBACKS uploader.onWhenAddingFileFailed = function (item, filter, options) { console.info(‘onWhenAddingFileFailed‘, item, filter, 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‘, fileItem, response, status, 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, response, status, headers) { console.info(‘onErrorItem‘, fileItem, response, status, headers); }; uploader.onCancelItem = function (fileItem, response, status, headers) { console.info(‘onCancelItem‘, fileItem, response, status, headers); }; uploader.onCompleteItem = function (fileItem, response, status, headers) { console.info(‘onCompleteItem‘, fileItem, response, status, headers); }; uploader.onCompleteAll = function () { console.info(‘onCompleteAll‘); }; } };});
2.如何使用
<!--filters 代表 你使用指令中的哪个过滤器 例如 imageFilter docFilter 具体看 directive.js中的 filtersmsg 提示语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; } } }
angular-file-upload封装为指令+图片尺寸限制
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。