package com.guwenren.utils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; /** * 图片验证工具类 * @author guwenren * */ public class ImageUtils { private static Properties properties = new Properties(); static { try { properties.load(ImageUtils.class.getClassLoader() .getResourceAsStream("arrowuploadfiletype.properties")); } catch (IOException e) { e.printStackTrace(); } } /** * 验证上传文件类型是否属于图片格式 * * @return */ public static boolean validateImageFileType(File logofile, String logofileFileName, String logofileContentType) { if (logofile != null && logofile.length() > 0) { // 类型 List<String> arrowType = Arrays.asList("image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg"); // 后缀名 List<String> arrowExtension = Arrays.asList("gif", "jpg", "bmp", "png"); String ext = getExt(logofileFileName); return arrowType.contains(logofileContentType.toLowerCase()) && arrowExtension.contains(ext); } return false; } /** * 验证上传文件是否属于图片/flash动画/word文件/exe文件/pdf文件/TxT文件/xls文件/ppt文件 * * @param formfile * @return */ public static boolean validateFileType(File file, String fileName, String fileType) { if (file != null && file.length() > 0) { String ext = getExt(fileName);// 得到上传文件的后缀名 List<String> arrowType = new ArrayList<String>();// 存储所有验证通过的文件类型 for (Object key : properties.keySet()) { String value = (String) properties.get(key); String[] values = value.split(","); for (String v : values) { arrowType.add(v.trim()); } } // 1文件的类型是否符合 2文件的后缀名是否符合 return arrowType.contains(fileType) && properties.keySet().contains(ext); } return false; } /** * 获取文件.后面的名称(.gif/gif)小写形式 * * @return */ public static String getExt(String fileName) { if (fileName != null && !"".equals(fileName)) { return fileName.substring(fileName.lastIndexOf('.') + 1) .toLowerCase(); } return null; } /** * 保存产品图片 * @param imageName * @param imagefile * @param typeid * @param productid * @throws IOException */ public static void saveProductImage(String imageName,File imagefile,Integer typeid,Integer productid) throws IOException{ // 图片后缀 String ext=getExt(imageName); // 保存路径 String saveimagepath = "/images/product/"+ typeid + "/"+ productid + "/prototype"; // 真实路径 String realimagepath = ServletActionContext.getServletContext().getRealPath(saveimagepath); File file = new File(realimagepath); if (!file.exists()) { file.mkdirs(); } FileUtils.copyFile(imagefile, new File(realimagepath, imageName)); // 保存路径 String saveimagepath140 = "/images/product/"+ typeid + "/"+ productid + "/140x"; // 真实路径 String realimagepath140 = ServletActionContext.getServletContext().getRealPath(saveimagepath140); File file140 = new File(realimagepath140); if (!file140.exists()) { file140.mkdirs(); } ImageSizer.resize(new File(realimagepath,imageName), new File(realimagepath140,imageName), 140, ext); } }