struts2 跟 commons-fileupload2.1 结合使用

struts2 和 commons-fileupload2.1 结合使用
昨天分析了很多错误,今天将正确的配置发布如下:
首先struts.properties中需要设置
struts.i18n.encoding=UTF-8
struts.locale=zh_CN
struts.multipart.saveDir=\temp
struts.multipart.maxSize=100000000
saveDir是struts2自带的上传功能,能够将附件临时保存在temp目录中。maxSize是附件大小,超过这个讲抛出异常。
使用了struts2自带的功能后,在上传时其实是不需要再次通过fileupload来获取。具体代码见下
request.setCharacterEncoding("UTF-8");
LoadPath loadPath = new LoadPath();
String rootPath = loadPath.getRootPath();
String path = "upload";
String fileName = "";
Util u = new Util();
// 判断有没有这个日期目录
String currData = u.getSysDate("yyyyMMdd");
// 判断目录在不,如果不在那么就添加一个目录
path = path + "/" + currData;
File dir = new File(path);
if (!dir.exists()) {
	// 不存在,需要创建目录
	try {
		dir.mkdir();
		this.log("创建目录:" + dir);
	} catch (Exception ex) {
		log.error("创建目录:" + path + "失败,原因:" + ex.toString());
	}
}

try {
	MultiPartRequestWrapper mrw = (MultiPartRequestWrapper)request;
	Enumeration<String> mu = mrw.getFileParameterNames();
	while(mu.hasMoreElements()){
		String name = mu.nextElement();
		System.out.println(request.getContentLength());
		File[] files  = mrw.getFiles(name);
		String[] fileNames = mrw.getFileNames(name);
		for(int i=0;i<files.length;i++){
			File file = files[i];
			fileName = fileNames[i];
			//保存file文件
			String oldName = fileName.substring(0, fileName
					.lastIndexOf("."));//旧文件名
			String fileNameAtt = fileName.substring(fileName
					.lastIndexOf(".") + 1, fileName.length());// 文件后缀名
			long time = System.currentTimeMillis();
			String newName = time + "." + fileNameAtt;
			long size = file.length();
			if (file.exists()) { // 文件存在时 
				FileInputStream fis=new FileInputStream(file);
				path += "/"+newName;
				FileOutputStream fs = new FileOutputStream(rootPath +"/"+ path); 
				byte[] buf = new byte[1024];  
			    int c;
			    while((c = fis.read(buf))!=-1)//返回实际读取到的大小
			    {
				fs.write(buf,0,c);
			    }
			    fs.flush(); //刷新缓冲区,记得
			    fs.close();
			    fis.close();
			}
			AppContext.getWySysFileManagerLogic().save(oldName, time+"", path, Integer.parseInt(size+""));
		}
		
	}
} catch (Exception e) {
	e.printStackTrace();
	log.info("文件上传失败!");
}

从上面可以看出,使用了MultiPartRequestWrapper mrw = (MultiPartRequestWrapper)request;来获取了上传附件的request.那么就可以获取到上传请求值,后来发现这个方法比其upload方法来说简单点。也可以获取到附件大小。