第31讲 .struts2文件下载

1在项目中,HeadFirstStruts2chapter08,新建fileDownLoadAction,getInputStream()方法名是固定的this.fileName="OtherMaterials.zip";再struts.xml中会用来取值,
package com.cruise.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport{

    private String fileName;

    public String getFileName() {
       return fileName;
    }
    public void setFileName(String fileName) {
       this.fileName = fileName;
    }
    
    public InputStream getInputStream()throws Exception{
       File file = new File("C:/Users/pengc/Desktop/OtherMaterials.zip");
       this.fileName="OtherMaterials.zip";
       return new FileInputStream(file);
    }
}
2配置struts.xml文件,${fileName}这里调用action中的getFileName()方法
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.multipart.maxSize" value="20000000"></constant>
    <package name="manager" extends="struts-default">
       <action name="fileDownLoad" class="com.cruise.action.FileDownloadAction">
           <result type="stream" >
              <param name="contentDisposition">attachment;filename=${fileName}</param>
           </result>
       </action> 
    </package>
</struts>

3fileDownload.jsp ,文件,
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="fileDownLoad" >文件下载</a>
</body>
</html>
4测试
http://localhost:8080/HeadFirstStruts2chapter08/fileDownload.jsp
5解决下载的文件名乱码的问题,FileDownloadAction 修改getFileName()方法
package com.cruise.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport{

    private String fileName;

    public String getFileName()throws Exception {
       fileName= new String(fileName.getBytes(),"ISO8859-1");
       return fileName;
    }
    public void setFileName(String fileName) {
       this.fileName = fileName;
    }
    
    public InputStream getInputStream()throws Exception{
       File file = new File("C:/Users/pengc/Desktop/材料.zip");
       this.fileName="文件.zip";
       return new FileInputStream(file);
    }
}
6测试
http://localhost:8080/HeadFirstStruts2chapter08/fileDownload.jsp

猜你喜欢

转载自blog.csdn.net/u010393325/article/details/83928798
今日推荐