最近在这几天做了个简单的文件下载功能,现在分享下,希望多多交流下。
1、页面代码
${proLoad.productDataName} <a href="<%=basePath%>Fpro_getDownLoad.action?fileName=${proLoad.productData}">下载</a>
将文件对应的路径 传到Action 中。
2、 Action 类中代码如下所示
public class ProductInfoAction extends ActionSupport{
// 产品资料地址
private String fileName;// 获得jsp中pram参数
private Iproduct productInfoImpl;
HttpServletRequest request = ServletActionContext.getRequest();
// 实现产品资料下载
public String getDownLoad() throws Exception {
// 得到产品资料ID
String showId = request.getParameter("showId");
productInfoImpl.updateLoadCount(showId);
return "downSuc";
}
//得到输出流
public InputStream getDownloadFile() throws Exception {
String fileName = request.getParameter("fileName");
ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.e ncode(fileName, "UTF-8"));
// System.out.println(getFileName()); // 如果下载文件名为中文,进行字符编码转换
InputStream inputStream = new FileInputStream(ServletActionContext.getServletContext().getRealPath("/" + fileName) ); // 使用绝对路径,从该路径下载文件
if (inputStream == null) {
return null;
}
return inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) throws Exception {
this.fileName = new String(fileName.getBytes("ISO-8859-1"), "utf-8");
}
}
Action 类中, fileName 是文件路径名; 给属性 get set ; getDownLoad() 为action 中方法 ; getDownloadFile() 为属性 downloadFile的get方法; 与struts.xml中配置对应.
3. Struts.xml 中配置
<action name="Fpro_*" class="proInfoAction" method="{1}"> <result name="downSuc" type="stream">
<!--指定文件下载类型 application/octet-stream默认值可以下载所有类型 -->
<param name="contentType">application/txt;</param>
<!-- 指定下载的文件名和显示方式 ,但注意中文名的乱码问题,解决办法是:进行编码处理-->
<!--contentDisposition是文件下载的处理方式,包括内联(inline)和附件(attachment), 默认是inline, 使用附件时这样配置 : attachment;filename="文件名" 。-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!--由getDownloadFile()方法获得inputStream-->
<param name="inputName">downloadFile</param>
<!--指定下载文件的缓存大小-->
<param name="bufferSize">2048</param>
</result>
</action>
其中 :filename 对应 action 类中的 fileName 属性。 downloadFile 对应 Action 中 getDownloadFile() 方法。
4. 文件下载中常见问题
最常见的问题如下:
java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action.
出现这个问题的原因如下 : 文件路径不正确 或着 该文件 不存在。