Struts2文件上依赖jar包:commons-io-1.3.2.jar、commons-fileupload-1.2.1.jar
1、首先在实体类,如User中中设置三个属性分别为:xxx、xxxContextType、xxxFileName.并提供相关的getter和sers方法。
//文件上传相关属性
private File upload;
private String uploadContentType;
private String uploadFileName;
2、在Action中提供下载方法,如名为fileupload方法:
public String fileupload() throws Exception {
//处理上传
if(user.getUpload() != null) {
String path = ServletActionContext.getServletContext().getRealPath("/upload");
File destFile = new File(path, user.getUploadFileName());
FileUtils.copyFile(user.getUpload(), destFile);
user.getUpload().delete();
user.setPath(path);
user.setFileName(user.getUploadFileName());
}
userService.save(user);
return "toList";
}
3、在struts.xml文件中配置对上传文件的属性限制,如上文文件的大小、扩展名等
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">20971520</param>
<!-- 配置上传文件允许的类型,如果配置多个值的话,用","隔开 -->
<param name="fileUpload.allowedTypes">text/plain,application/msword</param>
<!-- 配置上传文件的扩展名,如果配置多个值的话,用","隔开 -->
<param name="fileUpload.allowedExtensions">.txt</param>
</interceptor-ref>