后台上传方法
@RequestMapping(value = "/api_upload", method = RequestMethod.POST) public @ResponseBody String upload(HttpServletRequest request,HttpServletResponse response) { //获取上传路径 String uploadFilePath=ParameterConstants.UPLOAD_FILE_PATH; String storePath = ""; MultiparthttpServletRequest multipartreCeSt = (multiparthttpServletRequest) solicitação; // 获取前台传值 String [] pastas = multipartreCest.getParameTerValues ("caminho"); String pasta = ""; if (pastas! = null) {pasta = pastas [0]; storePath+= pasta+"/"; } Mapa <string, multipartfile> filemap = multipartrequest.getFilemap (); SimpledateFormat sdf = new SimpleDateFormat ("yyyyymm"); String ymd = sdf.format (new Date ()); storePath + = ymd + "/"; // 创建文件夹 arquivo de arquivo = novo arquivo (uploadFilePath+storePath); if (! file.exists ()) {file.mkdirs (); } String filename = null; Caminho da string = null; para (map.entry <string, multipartfile> entidade: filemap.entrySet ()) {// 上传文件名 MultartFile mf = entity.getValue (); nome do arquivo = mf.getoriginalfilename (); String uuid = uuid.randomuuid (). Tostring (). Replaceall ("// -", ""); // 返回一个随机 uuid。 string sufixo = nome do arquivo.indexof (".")! = -1? filename.substring (filename.lastIndexOF ("."), filename.length ()): null; String newFilename = uuid + (sufixo! = Null? Sufixo: ""); // 构成新文件名。 file uploadfile = novo arquivo (uploadFilePath + storePath + newFileName); tente { / ** * 验证上传文件的合法性 * / commonsmultipartFile cmf = (commonsmultipartFile) mf; boolean isValid = checkoutFiletype.getUpFileGitimacyFlag (cmf.getfileitem (), ". jpg.gif.png.jpeg"); if (! isValid) {System.out.println ("上传图片不合法"); retornar nulo; } FileCopyUtils.copy (mf.getBytes (), uploadfile); StorePath = StorePath + NewFileName; } catch (ioexception e) {e.printStackTrace (); }} retornar o storePath; }文件合法性验证类
pacote com.kaiyuan.common.util; importar java.io.fileInputStream; importar java.io.ioException; importar java.io.inputStream; importar java.util.hashmap; importar java.util.map; importar org.apache.commons.fileupload.fileitem; / ** * @Description: 处理上传附件, 校验是否合法 在服务器端判断文件类型的问题 , 故用获取文件头的方式 , * 直接读取文件的前几个字节 , 来判断上传文件是否符合格式 */ classe pública checkOutFileType {// 记录各个文件头信息及对应的文件类型 mapa estático público <string, string> mfiletypes = new hashmap <string, string> (); // 所有合法的文件后缀 public static string res_filetype = ".jpg.gif.png.jpeg"; estático {// imagens 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 ("0d0a0d0aa". mfiletypes.put ("0d0a2d2d", ".txt"); // txt mfiletypes.put ("0d0ab4b4", ".txt"); // txt mfiletypes.put ("b4b4bda8" ".txt"); ".txt"); // txt, 文件头部为英文字母 mfiletypes.put ("32323232", ".txt"); // txt, 文件头部内容为数字 mfiletypes.put ("0d0a09b4", ".txt"); // txt, 文件头部内容为数字 mfxtyPeSes.put ("31230" .txt "); // txt, 文件头部内容为数字 mfxtypes.put (" 31230.注意由于文本文档录入内容过多 , 则读取文件头时较为多变 -nd **/ 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 = novo byte [4]; if (é! = null) {tente {is.read (b, 0, b.Length); } catch (ioexception e) {e.printStackTrace (); }} retornar mfiletypes.get (getFileHeader (b)); } / ** * 根据文件转换成的字节数组获取文件头信息 * * @param filepath * 文件路径 * @return 文件头信息 * / public static string getfileheader (byte [] b) {string value = bytestoHexString (b); valor de retorno; } / ** * 将要读取文件头信息的文件的 Byte 数组转换成 String 类型表示 , , * 将字节数组的前四位转换成 16 进制字符串 , , , 要先和 0xff 做一次与运算。 * 这是因为 , 整个文件流的字节数组中 , 有很多是负数 , 进行了与运算后 , 可以将前面的符号位都去掉 , * 这样转换成的 16 进制字符串最多保留两位 , 如果是正数又小于 10 , , , 需要在前面补 0 , , @ @ @, , , 如果是正数又小于 如果是正数又小于 , 那么转换后只有一位 , * 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 = inteiro.tohexstring (src [i] e 0xff) .touppercase (); if (hv.Length () <2) {Builder.append (0); } builder.append (hv); } System.out.println ("获取文件头信息:" + builder.toString ()); retornar construtor.toString (); }/ ** * 判断上传的文件是否合法 (一) 、第一 : : 检查文件的扩展名 , (二) 、 第二 : : mime 类型。 * * @param AnextDoc * @return boolean */ public static boolean {booleanfl up (bóia! {StringnetName = AnexeDoc.getName (); SNAME.TOLOWERCH (); {req_filetype = getFileType (ATCKDOC.GETINPUTINGSTREAM (); **/ if (req_filetype! = null &&! "". Equals (req_filetype) &&! "null" .equals (req_filetype)) {/ ** 第四步 : : 校验上传的文件扩展名 , 是否在其规定范围内 **/ if (allowType.ImExOf (RefiletyType)! } else {upflag = false; }} else { / ** 特殊情况校验, 如果用户上传的扩展名为, 文本文件, 则允许上传 -start ** / if (sname.indexof (". txt")! = -1) {upflag = true; } else {upflag = false; } / ** 特殊情况校验, 如果用户上传的扩展名为, 文本文件, 则允许上传 -nd ** /}}}} retorna upflag; }/** * 主函数 , 测试用 * * @param args * @throws exceção */public static void main (string [] args) lança exceção {// final string filetype = getFileType ("d: /bicp-huawei.mht"); FileInputStream é = null; String value = null; String filepath = "e: /aa/c.txt"; tente {is = new FileInputStream (filepath); byte [] b = novo byte [4]; is.read (B, 0, B.Length); valor = bytestoHexString (b); } catch (Exceção e) {} finalmente {if (null! = is) {try {is.close (); } catch (ioexception e) {}}} system.out.println (value); }}前端上传 JS
$ (document) .ready (function () {new textMagniFier ({inputElem: '#BankCardno', alinhe: 'top', splittype: [4,4,4,5], delimiter: ''}); $ ('#file_uplOad'). 'SWF': '$ {PageContext.Request.ContextPath} /js/upload/uploadify.swf', 'uploader': getBasepath ()+'/upload/api_upload; jSessionId = $ {PagecOntext.Session.id}', '$ {PageContext.request.ContextPath} /js/upload/uploadify-cancel.png', 'ButtonText': '' ',' Auto ': true,' multi ': true,' uploadlimit ': 100,' RemoveCompled ': True,' FiletypeText ': '*.jpg;*. gif;*. png;*. uploadfiles = $ (#Tickets "). Val (). }); }, 'onupLoaderror': function (arquivo, errorCode, errorMsg, errorString) {if (errorString.indexof ('o limite de upload foi alcançado')) {layer.msg (errorstring); }}, 'oneselect': function (file) {// alert ('o arquivo' + file.name + 'foi adicionado à fila.'); isuploadSuccess = false; }, 'OneSelecterRor': function (arquivo, erroCode, errorMsg) {switch (errorCode) {case -110: camada.msg ("文件大小超过了 2m"); quebrar; caso -100: camada.msg ("最多上传 5 张图片"); quebrar; padrão: layer.msg (errorMsg); }}, 'OnDialogClose': function (Queuedata) {var uPLOPLFILES = $ ("#Tickets"). val (). Split (','); var uPLOPLEFILESIZE = UPLOPLEFILES.LENGENS; if (uploadFilesize> 5) {Layer.msg ("最多上传 5 张图片"); Queuedata.Filesselected = 0 retornar false; }}}); onquery (); });以上所述是小编给大家介绍的 Carregue 上传及后台文件合法性验证的代码解析 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!