後台上傳方法
@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(); });以上所述是小編給大家介紹的上傳上傳及後台文件合法性驗證的代碼解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持! ,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!