本篇主要介绍使用Struts2实现文件的动态下载,此篇是在上一篇http://my.oschina.net/ski/blog/41117(文件上传)的基础上做的。
POJO类与上一篇的相同。
下面着重是Action类的写法。
package com.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import com.common.base.BaseAction;
import com.common.util.Configuration; //一个自定义的properties文件读取类。
import com.entity.FileBag;
import com.opensymphony.xwork2.ModelDriven;
import com.service.FileBagService;
public class FileDownloadAction extends BaseAction implements ModelDriven<FileBag> {
private InputStream download; //实现文件下载,必须要有
private String filename;//文件的表示出来的名称
private String realName;//表示文件存的实际名称
private String contentType; //文件类型
@Autowired
private FileBagService fileBagService;
private FileBag fileBag = new FileBag();
public InputStream getDownload() {
return this.download;
}
@Override
public String execute() throws Exception {
//从数据库根据Id读取出文件记录
this.fileBag = fileBagService.getOneFileBagById(fileBag.getId());
this.realName = fileBag.getFilePath();//获取并设定文件存储的随机字符串名
this.filename = fileBag.getFileName(); //获取并设定真实的文件名称
this.contentType = fileBag.getFileType(); //获取并设定文件的类型
fileBag.setDownloadCount(fileBag.getDownloadCount()+1); //下载次数加1
fileBagService.update(fileBag); //更新该文件记录
File file = new File(Configuration.getValue("fileSaveDir")+this.realName); //获得该文件的file对象
InputStream in = new FileInputStream(file); //创建文件对象的流对象
setDownload(in); //对流对象进行设定
return SUCCESS;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setDownload(InputStream download) {
this.download = download;
}
public FileBag getModel() {
return fileBag;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
下一步是 struts2的xml的配置
<global-results>//定义exception页面
<result name="exception">error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="exception" exception="java.lang.Exception"/>
</global-exception-mappings>
<!-- 文件下载 -->
<action name="fileDownloadAction" class="com.action.FileDownloadAction">
<exception-mapping result="fileNotFoundException" exception="java.io.FileNotFoundException"></exception-mapping>
<result name="success" type="stream">
<param name="contentType">${contentType}</param>
<param name="contentDisposition">attachment;filename="${filename}"</param>
<param name="inputName">download</param>
</result>
<result name="fileNotFoundException">/file/exception.jsp</result>
</action>
写到这里,文件下载的核心代码就完成了。
至于实体类的业务查询,那些基础,本篇不做介绍。