uploadify上傳及後台檔案合法性驗證的代碼解析_java

來源:互聯網
上載者:User

後台上傳方法

@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上傳及後台檔案合法性驗證的代碼解析,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.