文件下载struts2
第一步:struts2文件下载 xml配置
?
<action name="download"
??? ??? ??? type="stream">
??? ??? ??? ??? <!-- 类型-->
??? ??? ??? ??? <param name="contentType">text/plain</param>
??? ??? ??? ??? <!-- 前台链接参数 -->
??? ??? ??? ??? <param name="contentDisposition">
??? ??? ??? ??? ??? attachment;filename="${downloadChineseFileName}"
??? ??? ??? ??? </param>
??? ??? ??? ??? <!--? -->
??? ??? ??? ??? <param name="inputName">downloadFile</param>
??? ??? ??? </result>
??? ??? ??? <result name="downloaderror" type="chain">
??? ??? ??? ??? showResList
??? ??? ??? </result>
??? ??? </action>
?
第二步: 类的实现
package action.netDiskAction;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
?* 个人中心资源问答下载附件实现
?*
?* @author huyt
?*
?*/
public class DownloadAction extends ActionSupport {
??? private String fileName; // 文件名和文件路径
??? private String newFileName; // 用于下载后显示的文件名
??? private boolean isExists; // 用户判断文件是否存在
??? private int toPage; // 下载资源所在的当前页面
??? // 从下载文件原始存放路径读取得到文件输出流
??? public InputStream getDownloadFile() {
??? ??? return ServletActionContext.getServletContext().getResourceAsStream(
??? ??? ??? ??? "/" + fileName);
??? }
??? // 如果下载文件名为中文,进行字符编码转换
??? public String getDownloadChineseFileName() {
??? ??? String downloadChineseFileName = newFileName;
??? ??? try {
??? ??? ??? downloadChineseFileName = new String(downloadChineseFileName
??? ??? ??? ??? ??? .getBytes(), "ISO8859-1");
??? ??? } catch (UnsupportedEncodingException e) {
??? ??? ??? e.printStackTrace();
??? ??? }
??? ??? return downloadChineseFileName;
??? }
??? public String execute() {
??? ??? String basePath = ServletActionContext.getServletContext().getRealPath(
??? ??? ??? ??? "");
??? ??? String filePath = basePath + fileName;
??? ??? File file = new File(filePath);
??? ??? if (!file.exists()) {
??? ??? ??? HttpServletRequest request = ServletActionContext.getRequest();
??? ??? ??? request.setAttribute("message", "文件已经不存在,请联系管理员!");
??? ??? ??? // 如果topage为0时,说明在第一页,需要进行重新设置为1
??? ??? ??? if (toPage == 0) {
??? ??? ??? ??? toPage = 1;
??? ??? ??? }
??? ??? ??? return "downloaderror";
??? ??? } else {
??? ??? ??? return SUCCESS;
??? ??? }
??? }
??? public String getFileName() {
??? ??? return fileName;
??? }
??? public void setFileName(String fileName) {
??? ??? this.fileName = fileName;
??? }
??? public String getNewFileName() {
??? ??? return newFileName;
??? }
??? public void setNewFileName(String newFileName) {
??? ??? this.newFileName = newFileName;
??? }
??? public int getToPage() {
??? ??? return toPage;
??? }
??? public void setToPage(int toPage) {
??? ??? this.toPage = toPage;
??? }
}