在做学校项目的时候需要用到文件上传和下载的功能,项目框架是SSI,这里给出单文件下载的简单示例。
1. 需要的jar包:
(1)commons-fileupload-1.2.2.jar
(2)commons-io-2.0.1.jar
2.JSP
<a href="templateDownlod.action" id="downBtn" style="width: 100px;padding : 5px;">下载数据模板</a>
3.Struts的配置
<!-- Excel模板文件下载 -->
<action name="templateDownlod" class="com.model.action.GermAction">
<param name="templatePath">/template/录入模板.XLSX</param>
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">excelTemplate</param> <!-- 这个excelTemplate名字要和Action中的getExcelTemplate()方法名去掉get 一致 -->
<param name="contentDisposition">attachment;filename=${templateName}</param> <!-- attachment :下载时会打开下载框 fileName="${fileName}" :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字-->
</result>
</action>
4.Action
private String templatePath;// 下载文件路径(貌似只需要这一个属性就可以解决下载问题)
public String getTemplatePath() {
return templatePath;
}
public void setTemplatePath(String templatePath) {
this.templatePath = templatePath;
}
/**
* 获取模板文件名(解决中文乱码)这里的templateName对应action配置里的filename=${templateName},需要配置get方法
* @author: LS
* 2016-9-20 下午5:37:49
* @return
* @throws UnsupportedEncodingException String
*/
public String getTemplateName() throws UnsupportedEncodingException {
//解决乱码
return URLEncoder.encode("录入模板.XLSX", "UTF-8");
}
/**
* 下载文件的方法,返回类型必须是InputStream流
* @author: LS
* 2016-9-20 下午8:26:08
* @return
* @throws Exception InputStream
*/
public InputStream getExcelTemplate() throws Exception {
System.out.println("templatePath=" + templatePath);
return ServletActionContext.getServletContext().getResourceAsStream(templatePath);
}
单文件上传见http://blog.csdn.net/sunglee_1992/article/details/53033433