struts2实现下载功能
一,关于struts.xml参数
<!-- 文件下载 -->
<action name="downloadFile" class="ut.action.DownloadAction">
<result name="success" type="stream">
<!--设置为图片,其他类型见下-->
<param name="contentType">image/jpeg;charset=ISO8859-1</param>
<!--下载文件流-->
<param name="inputName">inputStream</param>
<!--添加参数,即就是下载的名称-->
<param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
<!--缓存-->
<param name="bufferSize">4096</param>
</result>
</action>
1、contentDisposition:文件下载的处理方式:包括内联(inline)和附件(attachment),附件方式会弹出保存文件的对话框,否则浏览器会尝试直接显示文件。一般默认值为attachment;filename="${downloadFileName}",其中,filename表示使用经过转码的文件名作为下载文件名,""号中间既可以直接加文件名,又可以将调用该Action中的getDownloadFileName方法。{}内,一定要去掉get并把第一个大写字母变小写。
困扰1:乱码问题。
2、contentType:下载文件的文件类型,和互联网MIME标准钟的规定类型一致,application/octet-stream 表示无限制。其他类型见附言。
3、inputName:下载文件的来源流,通常就是“流对象名”,对应着action类中某个InputStream类型的属性名,例如:取值为inputStream的属性需要编写getInputStream()方法。一旦xml文件读到inputStream,它就会自动去找Action中的getInputStream方法。
4、bufferSize表示下载缓冲区的大小。
二,action类的编写
public class DownloadAction extends ActionSupport {
/** 文件名 转换编码 防止中文乱码*/
public String getDownloadFileName() {
String fileName=ServletActionContext.getRequest().getParameter("fileName");
String downloadFileName = fileName;
try {
downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return downloadFileName;
}
//下载的流
public InputStream getInputStream() {
String name=this.getDownloadFileName();
System.out.println(name);
String realPath="/uploadImages/"+name;
InputStream in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
if(null==in){
System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");
}
return ServletActionContext.getServletContext().getResourceAsStream(realPath);
}
public String execute(){
return "success";
}
需要注意的就是使用getResourceAsStream方法时,文件路径必须是以“/”开头,且是相对路径。这个路径是相对于项目根目录(WEBRoot下)的。
可以用return new FileInputStream(realPath)的方法来得到绝对路径的文件。
三,测试
在WEBRoot下建立一个文件包,uploadImages,里面放上你要上传的文件(我这里是图片),
然后,html中是
<href="<%=path %>/downloadFile.action?fileName=${request.img}>">立刻下载</a>
<a href="<%=basePath%>system/download.action?fileName=使用手册.rar" target="_blank" class="gv">下载</a>
<!--上面的${request.img},就是你要上传的图片名称,而这样个图片名称是在这之前就从数据库中获取好的-->