后台上传方法
@requestmapping(value =“/api_upload”,method = requestMethod.post)public @Responsebody string upload(httpservletrequest request,httpservletResponse响应响应){//获取上传路径字符串uploadfilepath = uploadfilepath = parameterContants.upload_file_file_file_path; String StorePath =“”; MultiparthttpservletRequest ultipartrequest =(MultiparthttpservletRequest)请求; //获取前台传值string []文件夹= supertartrequest.getParameTervalues(“ path”);字符串文件夹=“”;如果(文件夹!= null){文件夹=文件夹[0]; StorePath+=文件夹+“/”; } map <string,MultipartFile> filemap = supertartrequest.getFileMap(); SimpleDateFormat SDF =新的SimpleDateFormat(“ Yyyymm”);字符串ymd = sdf.format(new Date()); StorePath + = ymd +“/”; //创建文件夹文件文件=新文件(uploadfilepath+StorePath);如果(!file.exists()){file.mkdirs(); }字符串fileName = null;字符串路径= null; for(map.entry <string,multipartfile> entity:filemap.entryset()){//上传文件名多Artipartfile mf = entity.getValue();文件名= mf.getOriginalFileName();字符串uuid = uuid.randomuuid()。toString()。替换(“ //-”,“”); //返回一个随机uuid lincly。字符串suffix = filename.indexof(“。”)!= -1? filename.substring(filename.lastindexof(“。”),filename.length()):null;字符串newfileName = uuid +(suffix!= null?suffix:“”); //构成新文件名。文件uploadfile = new file(uploadfilepath + storepath + storepath + newfilename);尝试{ / ** *验证上传文件的合法性 * / commonsmultipartfile cmf =(CommonSmultipartFile)MF; boolean isValid = checkoutfiletype.getupfilelegitimacyflag(cmf.getfileitem(),“。jpg.gif.png.jpeg”); if(!isvalid){system.out.println(“上传图片不合法”);返回null; } filecopyutils.copy(mf.getbytes(),uploadfile); StorePath = StorePath + NewFileName; } catch(ioexception e){e.printstacktrace(); }} return StorePath; }文件合法性验证类
包com.kaiyuan.common.util;导入java.io.io.fileinputstream;导入java.io.ioexception;导入java.io.inputstream;导入java.util.hashmap;导入java.util.map;导入org.apache.commons.fileupload.fileitem; / ** * @description:处理上传附件,校验是否合法,故用获取文件头的方式, *, *直接读取文件的前几个字节,来判断上传文件是否符合格式 */ public ChackOutFileType {// public static Map <String,String,String> MfileTypes = mfiletypes = new Hashmap <string string,string> 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和CADMfileTypes.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/ **注意由于文本文档录入内容过多x,则读取文件头时较为多变-start **/ mfiletypes.put.put(“ 0d0a0a0d0a” mfiletypes.put(“ 0d0a2d2d”,“ .txt”); // txt mfiletypes.put(“ 0d00ab4b4”,“ .txt”); // txt mfiletypes.put(“ b4b4bda” “ .txt”); // txt,文件头部为英文字母mfiletypes.put(“ 32323232”,“ .txt”); // txt,文件头部内容为数字mfiletypes.put(“ 0d0a09b4”,“ .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”); //访问数据库文件MfileTypes.put(“ 46726f6d”,“ 46726f6d”,“ .mht”); mfiletypes.put(“ 4d494d45”,“ .mhtml”); } / ** * * * * * @param filepath *文件路径 * @return文件头信息 * / public static String getFileType(inputStream is){byte [] b = new byte [4];如果(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)b){字符串value = bytestohexstring(b);返回值; } / ** *将要读取文件头信息的文件的字字符串类型表示bytestohexstring(byte [] src){stringBuilder builder = new StringBuilder(); if(src == null || src.length <= 0){return null; }字符串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());返回builder.tostring(); }/ ** *((((((((二)),,):检查文件的mime类型字符串= getname(); sname.tolowercase(); / **第一步:检查文件扩展名{req_filetype = getfiletype(actactdoc.getInputstream());} catch(ioexception e){//第三步:检查文件扩展名,是否符合要求范围**/ if(req_filetype!= null &&!! } else {upflag = false; }} else { / **特殊情况校验,如果用户上传的扩展名为,文本文件,则允许上传 -start ** / if(sname.indexof(“。txt”)!= -1){upflag = true; } else {upflag = false; } / **特殊情况校验,如果用户上传的扩展名为,文本文件,则允许上传-end ** /}}}}}} return upflag; }/** *主函数,测试用 * * @param args * @throws异常 */public static void main(string [] args)抛出异常{//最终字符串filetype = getFileType = getFileType(“ d:/bicp-huawei.mht”); fileInputStream是= null;字符串值= null;字符串filepath =“ e:/aa/c.txt”;尝试{is = new FileInputStream(filepath);字节[] b = new Byte [4]; is.Read(b,0,b。长度); value = bytestohexstring(b); } catch(异常E){}最后{if(null!= is){try {is.close(); } catch(ioexception e){}}}} system.out.println(value); }}}前端上传js
$(document)。 'swf':'$ {pagecontext.request.contextpath}/js/upload/uploadify.swf','uploader':getBasepath()+'/upload/api_upload; '$ {pageContext.request.contextpath}/js/upload/uploadify-cancel.png','buttontext':'上传':'上传','auto':true,true,true,true,true,'uploadLimit':uploadlimit':100,'ememovected'ememovected': '*.jpg;*。gif;*。png;*。jpeg;','filesizelimit':'2MB','Filetypedesc':'上传'','onuploadSuccess':onuploadsuccess':function function(file,data,data,deconse) uploadfiles = $(“#tickets”)。 }); */} else {layer.msg(“上传失败”);} isuploadSuccess = true; 。 }},'OnSelect':function(file){// alert('file' + file.name +'已添加到队列中。'); isuploadSuccess = false; 。休息;案例-100:layer.msg(“最多上传5张图片”);休息;默认值:layer.msg(errormsg); }},'ondialogclose':function(queuedata){var uploadfiles = $(“#tickets”)。val()。split(',','); var uploadfilesize = uploadfiles.length; if(uploadFilesize> 5){layer.msg(“最多上传5张图片”); queuedata.filesselected = 0返回false; }}}); onQuery(); });以上所述是小编给大家介绍的上载上传及后台文件合法性验证的代码解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!