不了解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中的 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[];
var debugState = System.Configuration.ConfigurationManager.AppSettings["DebugState"];
var path = file.FileName.Substring(file.FileName.LastIndexOf("."));
var name = "qhLjlx/" + path + "/" + ((DateTime.Now.ToUniversalTime().Ticks - ) / ) + new Random().Next(, ); //时间戳
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封装为指令+图片尺寸限制的更多相关文章

  1. angular把echarts封装为指令(配合requirejs)

    1.在require中配置echartsjs文件 2.在directives下定义指令(定义为全局的指令,任何页面调用都可以) define(['app','echarts'],function(ap ...

  2. angularjs file upload插件使用总结

    之前由于项目需要,决定使用angularjs做前端开发,在前两个项目中都有文件上传的功能,因为是刚接触angularjs,所以对一些模块和模块间的依赖不是很了解.都是由其他大神搭好框架,我只做些简单的 ...

  3. jQuery File Upload 单页面多实例的实现

    jQuery File Upload 的 GitHub 地址:https://github.com/blueimp/jQuery-File-Upload 插件描述:jQuery File Upload ...

  4. jQuery File Upload文件上传插件简单使用

    前言 开发过程中有时候需要用户在前段上传图片信息,我们通常可以使用form标签设置enctype=”multipart/form-data” 属性上传图片,当我们点击submit按钮的时候,图片信息就 ...

  5. jQuery File Upload 判断图片尺寸,限定图片宽高的办法

    1.必须熟读jQuery File Upload 文档,在add方法中进行判断,如果不符合条件,就用 data.abort()方法取消上传动作. $("file").fileupl ...

  6. kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

    kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

  7. jQuery File Upload 图片上传解决方案兼容IE6+

    1.下载:https://github.com/blueimp/jQuery-File-Upload 2.命令: npm install bower install ================= ...

  8. springmvc处理上传图片代码(校验图片尺寸、图片大小)

    package com.maizuo.web.controller; import com.maizuo.domain.Result; import com.maizuo.util.Constants ...

  9. 上传文件 file upload 学习笔记

    这里我只会说说一些完成 file upload 的基础 API. 很多项目我们需要上传文件. 有简单的 input file, 有需要验证的,有需要压缩的(img),有需要分段的(video),有需要 ...

随机推荐

  1. struts异常:Caused by: Parent package is not defined: json-default - [unknown location]解决办法

    问题描述: Unable to load configuration. - [unknown location] at com.opensymphony.xwork2.config.Configura ...

  2. python_如何使用临时文件

    案例: 某项目中,从传感器中获得采集数据,每收集到1G的数据后做是数据分析,最终只保留数据分析的结果,收集到的数据放在内存中,将会消耗大量内存,我们希望把这些数据放到一个临时的文件中 临时文件不能命名 ...

  3. @media 针对不同的屏幕尺寸设置不同的样式

    @media screen and (max-width: 800px) {    #yanandownload .close input {    margin-right: 40px ;    } ...

  4. 错误:java.lang.NoClassDefFoundError: com/project/common/exception/ServiceException 的解决

    问题: 项目编译通过,启动报错误信息java.lang.NoClassDefFoundError: com/project/common/exception/ServiceException. 解决方 ...

  5. c++ singleton单例模式

    方法1:加锁的经典懒汉实现: class singleton { public: static pthread_mutex_t mutex; static singleton* initance(); ...

  6. mysql has gone away

    mysql出现ERROR : (2006, 'MySQL server has gone away') 的问题意思就是指client和MySQL server之间的链接断开了. 造成这样的原因一般是s ...

  7. 端口扫描命令nmap

    转:http://www.osyunwei.com/archives/2004.html 下面教大家在CentOS中用nmap查看主机端口: 一.安装nmap yum install nmap -y ...

  8. linux之cut命令简单用法

    语法 cut [-bn] [file] cut [-c] [file] cut [-df] [file] 使用说明: cut 命令从文件的每一行剪切字节.字符和字段并将这些字节.字符和字段写至标准输出 ...

  9. Lambda表达式详解 (转)

    前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸lambda吧:简化了匿名委托的使用,让你让代码更加简洁,优雅.据说它是微软自C#1.0后新增的最重要的功能之一 ...

  10. javascript中this指向问题

    本文参考http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html this是JavaScript的一个关 ...