`
java_mike
  • 浏览: 83753 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

上传文件类型验证工具类

阅读更多
1、定义合法文件类型的配置文件  allowuploadfiletype.properties
gif=image/gif
jpg=image/jpg,image/jpeg,image/pjpeg
bmp=image/bmp
png=image/png
swf=application/x-shockwave-flash
doc=application/msword
txt=text/plain
xls=application/vnd.ms-excel
ppt=application/vnd.ms-powerpoint
pdf=application/pdf
exe=application/octet-stream


2、验证工具类(从配置文件中读取可上传文件类型)
package cn.changtusoft.publicplatform.web.forms;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class Utils {

	/**
	 * 存放可上传文件,从配置文件中读取
	 * 
	 * 采用单例模式,只在类加载的时候读取一次,提高性能
	 */
	private static Properties pros = new Properties();
	static {
		try {
			pros.load(BaseActionForm.class.getClassLoader().getResourceAsStream("allowuploadfiletype.properties"));
		} catch (IOException e) {
			System.out.println("读取定义允许上传文件的配置文件失败!!!");
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 验证允许上传文件类型
	 * 
	 * @param formfile
	 * @return
	 */
	public boolean validateFileType(FormFile formfile) {
		if(formfile!=null && formfile.getFileSize()>0){
			
			// 用来保存合法文件类型
			List<String> allowType = new ArrayList<String>();
			Set keySet = pros.keySet();
			Iterator ite = keySet.iterator();
			while (ite.hasNext()) {
				String key = (String)ite.next();
				String values = pros.getProperty(key);
				// 转换为数组,类型
				String[] valueArray = values.split(",");
				for (String v : valueArray) {
					allowType.add(v);
				}
			}
			
			// 文件后缀名
			String ext = getFileExt(formfile);
			
			// 既判断文件的类型,也判断文件的后缀名,确保安全性
			return allowType.contains(formfile.getContentType().toLowerCase()) && pros.keySet().contains(ext);	
		}
		return false;
	}
	
	/**
	 * 验证上传图片格式是否合法
	 * 
	 * @param formfile
	 * @return
	 */
	public boolean validateImageFileType(FormFile formfile) {
		if(formfile!=null && formfile.getFileSize()>0){
			List<String> arrowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");
			return arrowType.contains(formfile.getContentType().toLowerCase());
		}
		
		return false;
	}
	
	/**
	 * 获取文件后缀名
	 * 
	 * 如:abc.gif  ===> gif
	 * 
	 * @param formFile
	 * @return
	 */
	public String getFileExt(FormFile formFile) {
		if (formFile != null) {
			String fileName = formFile.getFileName();
			return fileName.substring(fileName.lastIndexOf(".")+1);
		}
		return null;
	}
	
}


1
0
分享到:
评论
1 楼 nao000 2011-09-09  
感谢您的帖子带给的帮助。

相关推荐

Global site tag (gtag.js) - Google Analytics