后台上传方法
@requestmapping (value = "/api_upload", method = requestmethod.post) public @responsebody string upload (httpservletrequest request, httpservletresponse 응답) {// 获取上传路径 string uploadfilepath = parameterConstants.upload_file_path; String StorePath = ""; multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) 요청; // 获取前台传值 String [] 폴더 = multipartrequest.getParametErvalues ( "Path"); 문자열 폴더 = ""; if (폴더! = null) {folder = 폴더 [0]; StorePath+= 폴더+"/"; } map <String, multipartFile> filemap = multipartrequest.getFileMap (); simpledateformat sdf = new simpledateformat ( "yyyymm"); 문자열 ymd = sdf.format (new date ()); StorePath + = ymd + "/"; // 创建文件夹 파일 파일 = 새 파일 (uploadFilePath+StorePath); if (! file.exists ()) {file.mkdirs (); } 문자열 filename = null; 문자열 경로 = null; for (map.entry <string, multipartfile> entity : filemap.entryset ()) {// 上传文件名 multipartfile mf = entity.getValue (); filename = mf.getoriginalfilename (); String uuid = uuid.randomuuid (). toString (). replaceall ( "//-", ""); // 返回一个随机 uuid。 String subsix = filename.indexof ( ")! = -1? filename.substring (filename.lastindexof ( "."), filename.length ()) : null; 문자열 newFilename = uuid + (접미어! = null? 접미사 : ""); // 构成新文件名。 构成新文件名。 构成新文件名。 uploadfile = 새 파일 (uploadfilepath + storepath + newfilename); { / ** * 验证上传文件的合法性 * / commonsmultipartfile cmf = (commonsmultipartfile) mf; Boolean isvalid = CheckoutFileType.getUpFilEgitImacyFlag (cmf.getFileItem (), ". jpg.gif.png.jpeg"); if (! isvalid) {system.out.println ( "上传图片不合法"); 널 리턴; } filecopyutils.copy (mf.getBytes (), uploadfile); StorePath = StorePath + NewFilename; } catch (ioexception e) {e.printstacktrace (); }} return storepath; }文件合法性验证类
패키지 com.kaiyuan.common.util; import java.io.fileInputStream; import java.io.ioexception; import java.io.inputstream; java.util.hashmap import; java.util.map import; 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 m 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 ( "76666673", ".txt"); // txt, 文件头部为英文字母 mfiletypes.put ( "32323232", ".txt"); // txt, 文件头部内容为数字 mfiletypes.put ( "0d0a09b4", ".txt"); // txt, 文件头部内容为数字 mfiletypes.put ( "3132330d", "3132330d";注意由于文本文档录入内容过多, 则读取文件头时较为多变 -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); 반환 값; } / ** * * byte 数组转换成 string 类型表示 下面这段代码就是用来对文件类型作验证的方法 下面这段代码就是用来对文件类型作验证的方法 下面这段代码就是用来对文件类型作验证的方法 下面这段代码就是用来对文件类型作验证的方法 下面这段代码就是用来对文件类型作验证的方法 将字节数组的前四位转换成 16 进制字符串 进制字符串 进制字符串 进制字符串, 并且转换的时候 并且转换的时候 并且转换的时候, 要先和 0xff 做一次与运算。 * 这是因为 这是因为 整个文件流的字节数组中 整个文件流的字节数组中 有很多是负数 有很多是负数 有很多是负数 有很多是负数, 进行了与运算后 可以将前面的符号位都去掉, 可以将前面的符号位都去掉 可以将前面的符号位都去掉, * 这样转换成的 16 进制字符串最多保留两位 进制字符串最多保留两位, 如果是正数又小于 10, 那么转换后只有一位 那么转换后只有一位 需要在前面补 需要在前面补 0, 取完前四位这个循环就可以终止了 * * @param src 要读取文件头信息的文件的 * / private static bytestoHexString (byte [] src) {StringBuilder builder = new StringBuilder (); if (src == null || src.length <= 0) {return null; } 문자열 HV; for (int i = 0; i <src.length; i ++) {// 以十六进制 ay (基数 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 : 检查文件的 检查文件的 mime 类型 * * @param att {string att sname.tolowercase () : 是否符合要求范围 ** / if (sname) {upflag = true : 获取上传附件的文件头, 并获取其扩展名 直接读取文件的前几个字节 直接读取文件的前几个字节*防止上传附件变更扩展名绕过校验 *** / if (upflag) {req_fileType = getFileType (att **/ 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 Exception */public static void main (string [] args) 예외 {// 최종 문자열 filetype = getFileType ( "d : /bicp-huawei.mht"); FileInputStream은 = null; 문자열 값 = null; 문자열 filepath = "e : /aa/c.txt"; try {is = new FileInputStream (FilePath); 바이트 [] B = 새로운 바이트 [4]; is.read (b, 0, b.length); 값 = BytestoHexString (b); } catch (예외 e) {} 마지막으로 {if (null! = is) {try {is.close (); } catch (ioexception e) {}}} system.out.println (value); }}JS
$ (document). readay (function () {new TextMagnifier ({inputelem : '#BankCardNo', 'TOP', 'top', splitType : [4,4,4,5,5], Delimiter : ''}); $ ( '#file_upload'). 업로드 ({ 'formData': {/up road ' : '$ {pagecontext.request.contextpath} /js/upload/uploadify.swf', 'Uploader': getbasepath ()+'/upload/api_upload; '$ {pagecontext.request.contextpath} /js/upload/uploadify-cancel.png', 'buttontext': '上传', 'auto': true, 'multi': 'uploadlimit': 100, 'RemoveCempleted': 'filetypeexts': '*.jpg;*. gif;*. png;*. jpeg;', 'filesizelimit': '2mb', 'filetypedesc': '上传', 'onuploadsuccess': function (file, data, response) {if (data! = null && data.length> 0) {var uploadfiles = $ ( "#"). var uploadfiles. isuploadsuccess = true; }, 'onuploadError': 함수 (파일, errorcode, errormsg, errorstring) {if (errorstring.indexof ( '업로드 제한에 도달했습니다')) {layer.msg (errorstring); }}, 'onselect': function (file) {// alert ( '파일' + file.name + '가 큐에 추가되었습니다.'); isuploadsuccess = false; }, 'OnSeleCterror': function (file, errorCode, errormsg) {switch (errorCode) {case -110 : layer.msg ( "文件大小超过了 2m"); 부서지다; 사례 -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 return false; }}}); onquery (); });以上所述是小编给大家介绍的 업로드 ify, 希望对大家有所帮助, 如果大家有任何疑问请给我留言, 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!