因为没有使用jsp 作为展现层。前台全是extjs,导致struts2的文件上传拦截器虽然拦截了 文件大小,文件类型的错误,但是出错信息不能返回前台extjs。struts2默认要配置result input
No result defined for action ***Action and result input 所以只能在action中做校验,通过业务异常扔给json
/**
* 判断文件类型
* @param file 上传的文件
* @param type 上传文件需要类型(1.csv文件 2.图片文件)
* @param imageType 上传文件实际类型
* @param fileName 上传文件名
* @return
*/
public static boolean fileTypeValidate(File file,int type,String imageType,String... fileName){
if(file!=null){
try{
if(type==1){
if(!imageType.equals("application/vnd.ms-excel")){
return false;
}else {
String str = fileName[0].substring(fileName[0].lastIndexOf(".")).toLowerCase();
if(!str.equals(".csv")){
return false;
}
}
}else if(type==2){
if(!imageType.equals("image/png")&&!imageType.equals("image/gif")&&!imageType.equals("image/jpeg")&&!imageType.equals("image/bmp")){
return false;
}
}
}catch (Exception e){
return false;
}
}
return true;
}
/**
* 判断文件大小
* @param file 上传的文件
* @param size 上传的文件限制大小
* @return
*/
@SuppressWarnings("resource")
public static boolean fileSizeValidate(File file,int size){
if(file!=null){
try{
FileInputStream ins = new FileInputStream(file);
if (ins.available() > 1024 * 1024 * size) {
file.delete();
return false;
}
}catch (Exception e){
return false;
}
}
return true;
}