大家都知道struts2提供了文件下载的功能,很方便很好用。废话不多说直接开始。
首先我们先对struts.xml进行配置,struts2的result 类型设为stream,请看如下配置:
<span style="font-size:18px;"> <result name="toDownload" type="stream">
<param name="bufferSize">2048</param>
</result></span>1、contentType,这个和文件上传的一样,就是要下载文件的格式;
2、contentLength:这是要下载文件的文件大小;
3、contentDisposition:这个有两个属性:1、inline;2、attachment( contentDisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,就直接在网页上打开,不能直接打开的才会打开下载框自己选择,要想弹出下载框就用附件的形式attachment)
4、bufferSize:这是下载缓冲区的大小。(默认1024)
5、inputName:在定义输入流的名字。(默认inputStream)
这些属性可以在配置文件中定义,也可以在我们的java文件中定义,在这里我用的是在java文件中给以getter方法定义
private String contentType;
public String getContentType() {
return contentType;
}
public long getContentLength() {
return contentLength;
}
public String getContentDisposition() {
return contentDisposition;
}
private long contentLength;
private String contentDisposition;
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}文件批量下载需要用到ZipOutputStream这个的用法大家可以到网上自行百度。
下面贴上action内代码:
public String download()throws Exception{
String FilePath= ServletActionContext.getServletContext()//获取路径
.getRealPath("/images/");
File zipFile=new File(ServletActionContext.getServletContext()//定义所要输入文件的zip文件
.getRealPath("images/testdownload/zipFile.zip"));
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(zipFile));
int temp = 0 ;
FileInputStream input=null;
for (int i = 0; i < fileName.length; i++) {
File Files=new File(FilePath+"\\"+fileName[i]);
input=new FileInputStream(Files);
zos.putNextEntry(new ZipEntry(Files.getName()+File.separator+fileName[i]));//将文件加入到Entry中
while((temp=input.read())!=-1){ // 读取内容
zos.write(temp) ; // 压缩输出
}
}
input.close();
zos.close();
contentType="application/x-zip-compressed";//设定文件类型为.zip文件
contentDisposition="attachment;filename=test.zip";//设定文件名为test.zip
inputStream=new FileInputStream(zipFile); //定义流
System.out.println(inputStream);
contentLength=inputStream.available();
return"toDownload";
}
原文:http://blog.csdn.net/nethackatschool/article/details/43018161