当前位置: 移动技术网 > IT编程>开发语言>Java > uploadify上传及后台文件合法性验证的代码解析

uploadify上传及后台文件合法性验证的代码解析

2019年07月22日  | 移动技术网IT编程  | 我要评论

后台上传方法

@requestmapping(value = "/api_upload", method = requestmethod.post) 
public @responsebody string upload(httpservletrequest request,httpservletresponse response) { 
//获取上传路径 
string uploadfilepath=parameterconstants.upload_file_path; 
string storepath=""; 
multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request; 
// 获取前台传值 
string[] folders = multipartrequest.getparametervalues("path"); 
string folder = ""; 
if (folders != null) { 
folder = folders[0]; 
storepath+=folder+"/"; 
} 
map<string, multipartfile> filemap = multipartrequest.getfilemap(); 
simpledateformat sdf = new simpledateformat("yyyymm"); 
string ymd = sdf.format(new date()); 
storepath += ymd + "/"; 
// 创建文件夹 
file file = new file(uploadfilepath+storepath); 
if (!file.exists()) { 
file.mkdirs(); 
} 
string filename = null; 
string path = null; 
for (map.entry<string, multipartfile> entity : filemap.entryset()) { 
// 上传文件名 
multipartfile mf = entity.getvalue(); 
filename = mf.getoriginalfilename(); 
string uuid = uuid.randomuuid().tostring().replaceall("\\-", "");// 返回一个随机uuid。 
string suffix = filename.indexof(".") != -1 ? filename.substring( 
filename.lastindexof("."), filename.length()) : null; 
string newfilename = uuid + (suffix != null ? suffix : "");// 构成新文件名。 
file uploadfile = new file(uploadfilepath+storepath + newfilename); 
try { 
/** 
* 验证上传文件的合法性 
*/ 
commonsmultipartfile cmf =(commonsmultipartfile)mf; 
boolean isvalid=checkoutfiletype.getupfilelegitimacyflag(cmf.getfileitem(),".jpg.gif.png.jpeg"); 
if(!isvalid){ 
system.out.println("上传图片不合法"); 
return null; 
} 
filecopyutils.copy(mf.getbytes(), uploadfile); 
storepath = storepath + newfilename; 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
return storepath; 
}

文件合法性验证类

package com.kaiyuan.common.util; 
import java.io.fileinputstream; 
import java.io.ioexception; 
import java.io.inputstream; 
import java.util.hashmap; 
import java.util.map; 
import org.apache.commons.fileupload.fileitem; 
/** 
* @description: 处理上传附件,校验是否合法 在服务器端判断文件类型的问题,故用获取文件头的方式, 
* 直接读取文件的前几个字节,来判断上传文件是否符合格式 
*/ 
public class checkoutfiletype { 
// 记录各个文件头信息及对应的文件类型 
public static map<string, string> mfiletypes = new hashmap<string, string>(); 
// 所有合法的文件后缀 
public static string res_filetype = ".jpg.gif.png.jpeg"; 
static { 
// images 
mfiletypes.put("ffd8ffe0", ".jpg"); 
mfiletypes.put("89504e47", ".png"); 
mfiletypes.put("47494638", ".gif"); 
mfiletypes.put("49492a00", ".tif"); 
mfiletypes.put("424d", ".bmp"); 
// ps和cad 
mfiletypes.put("38425053", ".psd"); 
mfiletypes.put("41433130", ".dwg"); // cad 
mfiletypes.put("252150532d41646f6265", ".ps"); 
// 办公文档类 
mfiletypes.put("d0cf11e0", ".doc"); // ppt、doc、xls 
mfiletypes.put("504b0304", ".docx");// pptx、docx、xlsx 
/** 注意由于文本文档录入内容过多,则读取文件头时较为多变-start **/ 
mfiletypes.put("0d0a0d0a", ".txt");// txt 
mfiletypes.put("0d0a2d2d", ".txt");// txt 
mfiletypes.put("0d0ab4b4", ".txt");// txt 
mfiletypes.put("b4b4bda8", ".txt");// 文件头部为汉字 
mfiletypes.put("73646673", ".txt");// txt,文件头部为英文字母 
mfiletypes.put("32323232", ".txt");// txt,文件头部内容为数字 
mfiletypes.put("0d0a09b4", ".txt");// txt,文件头部内容为数字 
mfiletypes.put("3132330d", ".txt");// txt,文件头部内容为数字 
/** 注意由于文本文档录入内容过多,则读取文件头时较为多变-end **/ 
mfiletypes.put("7b5c727466", ".rtf"); // 日记本 
mfiletypes.put("255044462d312e", ".pdf"); 
// 视频或音频类 
mfiletypes.put("3026b275", ".wma"); 
mfiletypes.put("57415645", ".wav"); 
mfiletypes.put("41564920", ".avi"); 
mfiletypes.put("4d546864", ".mid"); 
mfiletypes.put("2e524d46", ".rm"); 
mfiletypes.put("000001ba", ".mpg"); 
mfiletypes.put("000001b3", ".mpg"); 
mfiletypes.put("6d6f6f76", ".mov"); 
mfiletypes.put("3026b2758e66cf11", ".asf"); 
// 压缩包 
mfiletypes.put("52617221", ".rar"); 
mfiletypes.put("1f8b08", ".gz"); 
// 程序文件 
mfiletypes.put("3c3f786d6c", ".xml"); 
mfiletypes.put("68746d6c3e", ".html"); 
mfiletypes.put("7061636b", ".java"); 
mfiletypes.put("3c254020", ".jsp"); 
mfiletypes.put("4d5a9000", ".exe"); 
mfiletypes.put("44656c69766572792d646174653a", ".eml"); // 邮件 
mfiletypes.put("5374616e64617264204a", ".mdb");// access数据库文件 
mfiletypes.put("46726f6d", ".mht"); 
mfiletypes.put("4d494d45", ".mhtml"); 
} 
/** 
* 根据文件的输入流获取文件头信息 
* 
* @param filepath 
* 文件路径 
* @return 文件头信息 
*/ 
public static string getfiletype(inputstream is) { 
byte[] b = new byte[4]; 
if (is != null) { 
try { 
is.read(b, 0, b.length); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
return mfiletypes.get(getfileheader(b)); 
} 
/** 
* 根据文件转换成的字节数组获取文件头信息 
* 
* @param filepath 
* 文件路径 
* @return 文件头信息 
*/ 
public static string getfileheader(byte[] b) { 
string value = bytestohexstring(b); 
return value; 
} 
/** 
* 将要读取文件头信息的文件的byte数组转换成string类型表示 下面这段代码就是用来对文件类型作验证的方法, 
* 将字节数组的前四位转换成16进制字符串,并且转换的时候,要先和0xff做一次与运算。 
* 这是因为,整个文件流的字节数组中,有很多是负数,进行了与运算后,可以将前面的符号位都去掉, 
* 这样转换成的16进制字符串最多保留两位,如果是正数又小于10,那么转换后只有一位, 
* 需要在前面补0,这样做的目的是方便比较,取完前四位这个循环就可以终止了 
* 
* @param src要读取文件头信息的文件的byte数组 
* @return 文件头信息 
*/ 
private static string bytestohexstring(byte[] src) { 
stringbuilder builder = new stringbuilder(); 
if (src == null || src.length <= 0) { 
return null; 
} 
string hv; 
for (int i = 0; i < src.length; i++) { 
// 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式,并转换为大写 
hv = integer.tohexstring(src[i] & 0xff).touppercase(); 
if (hv.length() < 2) { 
builder.append(0); 
} 
builder.append(hv); 
} 
system.out.println("获取文件头信息:" + builder.tostring()); 
return builder.tostring(); 
} 
/** 
* 判断上传的文件是否合法 (一)、第一:检查文件的扩展名, (二)、 第二:检查文件的mime类型 。 
* 
* @param attachdoc 
* @return boolean 
*/ 
public static boolean getupfilelegitimacyflag(fileitem attachdoc,string allowtype) { 
boolean upflag = false;// 为真表示符合上传条件,为假表标不符合 
if (attachdoc != null) { 
string attachname = attachdoc.getname(); 
system.out.println("#######上传的文件:" + attachname); 
if (!"".equals(attachname) && attachname != null) { 
/** 返回在此字符串中最右边出现的指定子字符串的索引 **/ 
string sname = attachname 
.substring(attachname.lastindexof(".")); 
/** 统一转换为小写 **/ 
sname = sname.tolowercase(); 
/** 第一步:检查文件扩展名,是否符合要求范围 **/ 
if (allowtype.indexof(sname) != -1) { 
upflag = true; 
} 
/** 
* 第二步:获取上传附件的文件头,判断属于哪种类型,并获取其扩展名 直接读取文件的前几个字节,来判断上传文件是否符合格式 
* 防止上传附件变更扩展名绕过校验 
***/ 
if (upflag) { 
byte[] b = new byte[4]; 
string req_filetype = null; 
try { 
req_filetype = getfiletype(attachdoc.getinputstream()); 
} catch (ioexception e) { 
// todo auto-generated catch block 
e.printstacktrace(); 
} 
system.out.println("///////用户上传的文件类型///////////" 
+ req_filetype); 
/** 第三步:检查文件扩展名,是否符合要求范围 **/ 
if (req_filetype != null && !"".equals(req_filetype) 
&& !"null".equals(req_filetype)) { 
/** 第四步:校验上传的文件扩展名,是否在其规定范围内 **/ 
if (allowtype.indexof(req_filetype) != -1) { 
upflag = true; 
} else { 
upflag = false; 
} 
} else { 
/** 特殊情况校验,如果用户上传的扩展名为,文本文件,则允许上传-start **/ 
if (sname.indexof(".txt") != -1) { 
upflag = true; 
} else { 
upflag = false; 
} 
/** 特殊情况校验,如果用户上传的扩展名为,文本文件,则允许上传-end **/ 
} 
} 
} 
} 
return upflag; 
} 
/** 
* 主函数,测试用 
* 
* @param args 
* @throws exception 
*/ 
public static void main(string[] args) throws exception { 
// final string filetype = getfiletype("d:/bicp-huawei.mht"); 
fileinputstream is = null; 
string value = null; 
string filepath = "e:/aa/c.txt"; 
try { 
is = new fileinputstream(filepath); 
byte[] b = new byte[4]; 
is.read(b, 0, b.length); 
value = bytestohexstring(b); 
} catch (exception e) { 
} finally { 
if (null != is) { 
try { 
is.close(); 
} catch (ioexception e) { 
} 
} 
} 
system.out.println(value); 
} 
}

前端上传js

$(document).ready(function() { 
new textmagnifier({ 
inputelem: '#bankcardno', 
align: 'top', 
splittype: [4,4,4,5,5], 
delimiter:' ' 
}); 
$('#file_upload').uploadify({ 
'formdata' : { 
'path':'/uploadfilepath', 
}, 
'swf' : '${pagecontext.request.contextpath}/js/upload/uploadify.swf', 
'uploader' : getbasepath()+'/upload/api_upload;jsessionid=${pagecontext.session.id}', 
'cancelimg' : '${pagecontext.request.contextpath}/js/upload/uploadify-cancel.png', 
'buttontext': '上传', 
'auto' : true, 
'multi' : true, 
'uploadlimit':100, 
'removecompleted':true, 
'filetypeexts': '*.jpg;*.gif;*.png;*.jpeg;', 
'filesizelimit':'2mb', 
'filetypedesc': '上传', 
'onuploadsuccess':function(file,data,response) { 
if(data!=null && data.length>0){ 
var uploadfiles=$("#tickets").val().split(','); 
var uploadfilesize=uploadfiles.length; 
if(uploadfilesize>5){ 
layer.msg("最多上传5张图片"); 
return ; 
} 
addtickets(data); 
/* layer.ready(function(){ 
layer.photos({ 
photos: '#imgshow', 
shade:0.5 
}); 
}); */ 
}else{ 
layer.msg("上传失败"); 
} 
isuploadsuccess=true; 
}, 
'onuploaderror':function(file, errorcode, errormsg, errorstring) { 
if(errorstring.indexof('the upload limit has been reached')){ 
layer.msg(errorstring); 
} 
}, 
'onselect' : function(file) { 
//alert('the file ' + file.name + ' was added to the queue.'); 
isuploadsuccess=false; 
}, 
'onselecterror' : function(file, errorcode, errormsg){ 
switch(errorcode){ 
case -110: 
layer.msg("文件大小超过了2m"); 
break; 
case -100: 
layer.msg("最多上传5张图片"); 
break; 
default: 
layer.msg(errormsg); 
} 
}, 
'ondialogclose' : function(queuedata) { 
var uploadfiles=$("#tickets").val().split(','); 
var uploadfilesize=uploadfiles.length; 
if(uploadfilesize>5){ 
layer.msg("最多上传5张图片"); 
queuedata.filesselected=0 
return false; 
} 
} 
}); 
onquery(); 
});

以上所述是小编给大家介绍的uploadify上传及后台文件合法性验证的代码解析,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网