后台上传方法
@RequestMapping (valor = "/api_upload", método = requestmethod.post) public @ResponseBody String upload (httpservletRequest request, httpservletResponse respuesta) {// 获取上传路径 String uploadFilePath = parameterConstants.upload_file_path; String storePath = ""; MultiparthttpservletRequest multipertecequest = (multipThttPservletRequest) solicitud; // 获取前台传值 String [] carpetas = multiparTruCest.getParametervalues ("ruta"); Carpeta de cadena = ""; if (carpetas! = null) {carpeta = carpetas [0]; storePath+= carpeta+"/"; } Map <string, multipartFile> fileMap = multiparTruCest.getFileMap (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyymm"); Cadena ymd = sdf.format (nueva fecha ()); storePath + = ymd + "/"; // 创建文件夹 Archivo de archivo = nuevo archivo (uploadFilePath+storePath); if (! file.exists ()) {file.mkdirs (); } Cadena filename = null; Ruta de cadena = nulo; for (map.entry <string, multipartFile> entity: fileMap.Entryset ()) {// 上传文件名 multipartfile mf = entity.getValue (); FileName = mf.getOriginalFileName (); String uuid = uuid.randomuuid (). ToString (). ReplaceAll ("// -", ""); // 返回一个随机 uuid。 string sufix = filename.indexof (".")! = -1? FileName.Substring (FileName.lastIndexof ("."), FileName.Length ()): null; String newFileName = uuid + (sufix! = Null? Sufix: ""); // 构成新文件名。 archivo uploadFile = nuevo archivo (uploadFilePath + storePath + newFileName); intente { / ** * 验证上传文件的合法性 * / commonsMultipartFile cmf = (commonsMultipartFile) mf; boolean isValid = checkoutFileType.getUpfilelegitimacyFlag (cmf.getFileItem (), ". jpg.gif.png.jpeg"); if (! isValid) {System.out.println ("上传图片不合法"); regresar nulo; } FileCopyUtils.copy (mf.getBytes (), uploadFile); storePath = storePath + newFileName; } catch (ioException e) {E.PrintStackTrace (); }} return storePath; }文件合法性验证类
paquete com.kaiyuan.common.util; import java.io.fileInputStream; import java.io.ioException; import java.io.inputstream; import java.util.hashmap; import java.util.map; importar org.apache.commons.fileUpload.fileitem; / ** * @Description: 处理上传附件, 校验是否合法 在服务器端判断文件类型的问题 , 故用获取文件头的方式 , , * 直接读取文件的前几个字节 , 来判断上传文件是否符合格式 */ public class checkOutFileType {// 记录各个文件头信息及对应的文件类型 Mapa estático público <String, String> mfiletypes = new Hashmap <String, String> (); // 所有合法的文件后缀 public static string res_filetype = ".jpg.gif.png.jpeg"; static {// imágenes 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"); // txt, 文件头部为英文字母 mfiletypes.put ("32323232", ".txt"); // txt, 文件头部内容为数字 mfiletypes.put ("0d0a09b4", ".txt"); // txt, 文件头部内容为数字 mfiletypes.put ("3132330d", ".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"); // acceder 数据库文件 mfiletypes.put ("46726f6d", ".mht"); mfiletypes.put ("4D494D45", ".mhtml"); } / ** * 根据文件的输入流获取文件头信息 * * @param filepath * 文件路径 * @return 文件头信息 * / public static string getFileType (inputStream is) {byte [] b = nuevo 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); valor de retorno; } / ** * 将要读取文件头信息的文件的 byte 数组转换成 cadena 类型表示 下面这段代码就是用来对文件类型作验证的方法 , , * 将字节数组的前四位转换成 16 进制字符串 , , 并且转换的时候 , 要先和 0xff 做一次与运算。 * 这是因为 , 整个文件流的字节数组中 , , 进行了与运算后 , 可以将前面的符号位都去掉 , * 这样转换成的 16 进制字符串最多保留两位 , 如果是正数又小于 如果是正数又小于 10 , 那么转换后只有一位 , 需要在前面补 0 , 这样做的目的是方便比较 , 取完前四位这个循环就可以终止了 * * @param src 要读取文件头信息的文件的 数组 数组 数组 数组 数组 数组 * bytestoHexString (byte [] src) {StringBuilder Builder = new StringBuilder (); if (src == null || src.length <= 0) {return null; } Cadena 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 adjectDoc * @return boolean */ public static boolean getupfilelegitimacyFlag (fileItem adjectDoc, string teaTType) {boolean upflag = false; // 为真表示符合上传条件 为假表标不符合 为假表标不符合 if ((string nheLull) Attachdoc.getName (); sname.tolower (); {req_filetype = getFileType (adjunteDoc.getInputStream ());第三步 : 检查文件扩展名 , 是否符合要求范围 **/ if (req_filetype! = Nulo &&! "". Equals (req_filetype) &&! "Null" .equals (req_filetype)) {/ ** 第四步 : : 是否在其规定范围内 是否在其规定范围内 **/ if (teawType.indexof (req_filetype)! = -1)! } else {uplag = false; }} else { / ** 特殊情况校验, 如果用户上传的扩展名为, 文本文件, 则允许上传 -Start ** / if (sname.indexof (". txt")! = -1) {uplag = true; } else {uplag = false; } / ** 特殊情况校验, 如果用户上传的扩展名为, 文本文件, 则允许上传 -end ** /}}}} return upflag; }/** * 主函数 , 测试用 * * @param args * @throws excepción */public static void main (string [] args) lanza la excepción {// string final fileType = getFileType ("d: /bicp-huawei.mht"); FileInputStream is = null; Valor de cadena = nulo; Cadena filepath = "e: /aa/c.txt"; prueba {IS = nuevo FileInputStream (FilePath); byte [] b = nuevo byte [4]; IS.Read (B, 0, B.Length); valor = bytestoHexString (b); } catch (excepción e) {} finalmente {if (null! = is) {try {is.close (); } catch (ioException e) {}}} system.out.println (valor); }}前端上传 js
$ (documento) .Ready (function () {nuevo textMagnifier ({inputelem: '#BankCardNo', align: 'top', splittype: [4,4,4,5,5], delimiter: ''}); $ ('#file_upload'. '$ {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, respuesta) {if (data! = null && data.length> 0) {var var uploadFiles = $ ("#tickets"). Val (). Split (','); }); }, 'onUploadError': function (archivo, errorcode, errorMSG, errorString) {if (errorString.IndexOf ('se ha alcanzado el límite de carga')) {layer.msg (errorString); }}, 'onselect': function (file) {// alert ('el archivo' + file.name + 'se agregó a la cola.'); isuploadsuccess = false; }, 'onselECTERROR': function (archivo, errorcode, errormsg) {switch (errorcode) {case -110: layer.msg ("文件大小超过了 2m"); romper; Caso -100: Layer.msg ("最多上传 5 张图片"); romper; predeterminado: layer.msg (errormsg); }}, 'ondialogClose': function (queedata) {var uploadFiles = $ ("#tickets"). val (). Split (','); var uploadFilesize = uploadFiles.length; if (uploadFilesize> 5) {Layer.msg ("最多上传 5 张图片"); Queedata.filesSelected = 0 return false; }}}); onQuery (); });以上所述是小编给大家介绍的 Subir 上传及后台文件合法性验证的代码解析 , 希望对大家有所帮助 如果大家有任何疑问请给我留言 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!