struts2 上传文件
1)提交表单设置
Html代码
<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>选择文件</td>
<td>
<input type="file" name="upload" value=""/>
</td>
</tr>
<tr>
<td><input type="submit" value="上传文件" /></td>
</tr>
</table>
</form>
注意enctype一定要是"multipart/form-data"
2)Action代码
public class UploadAction extends ActionSupport {
private static final long serialVersionUID = 1224534552231961695L;
protected final Log logger = LogFactory.getLog(getClass());
private File upload; // 上传的临时文件
private String uploadContentType; // 文件的类型
private String uploadFileName; // 文件名
@Override
public String execute() throws Exception {
// 文件类型检查
if (! uploadContentType.equals("application/msword")) {
addFieldError("upload", "非法的上传文件类型");
return INPUT;
}
String tmpPath = ServletActionContext.getServletContext().getRealPath("tmp");
FileUtils.copyFile(upload, new File(tmpPath, uploadFileName)); // 拷贝文件
return SUCCESS;
}
// getter setter ...
}
3)配置Action strutsl.xml
<!-- ... -->
<action name="upload" class="net.csdn.struts.action.UploadAction">
<param name="allowedTypes">application/msword,text/html</param> <!-- 注入给Action用于配置允许上传类型 -->
<result name="success" type="dispatcher">/WEB-INF/jsp/success.jsp</result>
<result name="input" type="dispatcher">/index.jsp</result>
</action>
struts2 下载文件
1)DownloadAction
public class DownloadAction {
private String inputPath;
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public InputStream getTargetFile() {
return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}
public String execute() throws Exception {
return "success";
}
}
2)配置Action
<action name="download" class="net.csdn.struts.action.DownloadAction">
<param name="inputPath">/tmp/some.doc</param>
<result type="stream">
<!-- 文件类型 -->
<param name="contentType">application/msword</param>
<!-- Action中的InputStream -->
<param name="inputName">targetFile</param>
<!-- 设置文件名 -->
<param name="contentDisposition">filename="中文.doc"</param>
<!-- 缓存大小 -->
<param name="bufferSize">4096</param>
</result>
</action>