赠人玫瑰,手留余香.人生最大的快乐不在于占有什么而在于追求什么的过程.
参考文章:http://blog.csdn.net/happywzc110/article/details/7819037 http://hi.baidu.com/gujianting2010/item/ceb136f4a85ad0d26325d220 http://bbs.csdn.net/topics/390327422 http://bbs.csdn.net/topics/380264143
结合sturts2做文件上传的使用,如果使用common fileupload架包中的方法:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
在parseRequest的时候,经常会得到null。导致原因是struts2把原始的原来S2为简化上传功能,把所有的enctype="multipart/form-data"表单做了wrapper,最后把HttpServletResquest封装成 org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper 。
解决办法:imgFile:为input name=“imgFile”
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
File file = wrapper.getFiles("imgFile")[0];
String fileName = wrapper.getFileNames("imgFile")[0];
//检查文件大小
if(file.length() > maxSize){
String temStr= "上传文件大小超过限制。";
this.writeResponse(response, temStr);
return;
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
String temStr= "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。";
this.writeResponse(response, temStr);
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try {
InputStream in = new FileInputStream(file);
File uploadFile = new File(savePath, newFileName);
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}