1. 程式人生 > >第31講 .struts2檔案下載

第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