如何知道上传文件的类型并为他标识图标

如图,如果我的文件是什么格式的就在文件名前面加个与之匹配的小图标logo。

每个文件都会有个后缀,表示他的文件类型。比如 a.jpeg  b.txt  c.doc

要获取这个后缀然后判断。

具体使用那个图标,可以根据css定位。然后标签里加上对应的class。

.formatmin{display:inline-block;background:url(../imges/common/index_icon.png) no-repeat;width:22px;height:22px;vertical-align:middle;margin: 0 6px 2px 0;}   //放那个背景图的
.doc,.docx,.dotx,.dot,.docm,.dotm,.xps,.mht,.mhtml,.rtf,.xml,.odt{ background-position:-552px 0;}  //word文档
.xls,.xlsx,.xlsb,.xlsm,.xlst{background-position:-552px -28px;}   //excel表格
.ppt,.pptx{background-position:-552px -58px;}  //ppt文件
.pdf{background-position:-552px -88px;}  
.move,.mp4,.avi,.wmv,.f4v,.rm,.rmvb,.wmv,.mid,.mpeg,.mpg,.dat{background-position:-552px -116px;}  //视频
.jpg,.jpeg,.png,.gif,.bmp,.jpeg2000{background-position:-552px -146px;}  //图片
.flv,.swf,.flic,.flc,.fli,.flash{background-position:-552px -175px;}   //flash
.rar,.zip{background-position:-552px -204px;}   //压缩文件

.noknown,.unknown{background-position:-552px -261px;}  //其他未知的格式  


首先利用接口把数据传到后台,然后他会回传一个文件名。文件的url地址。文件的类型suffix。可能这个类型不是你上面写的那些,而是未知的。你就要比对一下了。写个函数看看是否你定义的那些里面的。

function getFormatClass(format){
var formatArr = [
"doc","docx","dotx","dot","docm","dotm","xps","mht","mhtml","rtf","xml","odt",
"pdf","ppt","pptx","xls","xlsx","xlsb","xlsm","xlst",
"jpg","jpeg","png","gif","bmp","jpeg2000",
"rar","zip",
"swf","flic","flc","fli","flash",
"mp4","avi","rm","rmvb","wmv","f4v","flv","mid","mpeg","mpg","dat"
];

if(typeof format != "undefined"){
format = $.trim(format).toLowerCase();
if($.inArray(format, formatArr) == -1){
return "unknown";
}else{
return format;
}
}else{
return "unknown";
}

}

假如suffix是接口传回来的关于类型的变量。

var suffix=getFormatClass(suffix);





你可能感兴趣的:(前端小知识)