src下建个properties文件,放置允许上传的文件类型:
allowuploadfiletype.properties

 
  
  1. gif=p_w_picpath/gif  
  2. jpg=p_w_picpath/jpg,p_w_picpath/jpeg,p_w_picpath/pjpeg  
  3. bmp=p_w_picpath/bmp  
  4. png=p_w_picpath/png  
  5. swf=application/x-shockwave-flash  
  6. doc=application/msword  
  7. txt=text/plain  
  8. xls=application/vnd.ms-excel  
  9. ppt=application/vnd.ms-powerpoint  
  10. pdf=application/pdf  
  11. exe=application/octet-stream  

BaseForm 里面写具体的验证方法:

 
  
  1. import java.io.IOException;  
  2. import java.util.ArrayList;  
  3. import java.util.Arrays;  
  4. import java.util.List;  
  5. import java.util.Properties;  
  6.  
  7. import org.apache.struts.action.ActionForm;  
  8. import org.apache.struts.upload.FormFile;  
  9.  
  10. public class BaseForm extends ActionForm {  
  11.  
  12.     private static Properties properties = new Properties();  
  13.  
  14.  
  15.     static{  
  16.         try {  
  17.             properties.load(BaseForm.class.getClassLoader().getResourceAsStream("allowuploadfiletype.properties"));  
  18.         } catch (IOException e) {  
  19.             e.printStackTrace();  
  20.         }   
  21.     }  
  22.       
  23.      
  24.     /**  
  25.     * 获取文件扩展名  
  26.     * @param formfile  
  27.     * @return 
  28.     */  
  29.     public static String getExt(FormFile formfile) {  
  30.         return formfile.getFileName().substring(  
  31.                 formfile.getFileName().lastIndexOf('.') + 1).toLowerCase();  
  32.     }  
  33.  
  34.     /**  
  35.     * 验证上传文件是否属于图片/flash动画/word文件/exe文件/pdf文件/TxT文件/xls文件/ppt文件  
  36.     *   
  37.     * @param formfile  
  38.     * @return 
  39.     */  
  40.     public static boolean validateFileType(FormFile formfile) {  
  41.         if (formfile != null && formfile.getFileSize() > 0) {  
  42.             String ext = getExt(formfile);  
  43.             List<String> allowType = new ArrayList<String>();  
  44.             for (Object key : properties.keySet()) {  
  45.                 String value = (String) properties.get(key);  
  46.                 String[] values = value.split(",");  
  47.                 for (String v : values) {  
  48.                     allowType.add(v.trim());  
  49.                 }  
  50.             }  
  51.             return allowType.contains(formfile.getContentType().toLowerCase())  
  52.                     && properties.keySet().contains(ext);  
  53.         }  
  54.         return true;  
  55.     }  
  56.