閱讀884 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Struts文件下載

 

這裏需要除了Struts本身需要的包以外,還有需要的包有:

commons-fileupload-1.2.1.jar

commons-io-1.4.jar


1 下載表單

我們當然可以讀出數據庫的文件名,可以對文件名進行處理,比如加上日期或者uuid使其唯一,那麼便可以唯一標識下載文件夾中的文件。

樣式1:
<form action="downLoad" method="post">
    <input type="hidden" value="<s:property value="#d.filename" />" name="fileName"/>
    <button type="submit">下載</button>
</form>


樣式2:
<a href="downLoad?filename=<s:property value="#d.filename" />">下載</a>

樣式1采用了post提交方式,而樣式2中的a標簽我們知道是get方式。
我們知道struts攔截器處理亂碼的時候,對post有效,對get無效。需要在tomcat裏麵設置才對get有效。
當然,你可以把按鈕的樣式做成鏈接的形式。

 

2 文件下載的Action

public class FileDownLoadAction extends ActionSupport
{

 private String fileName;

 public InputStream getInputStream() throws IOException
 {
  // 文件存放路徑
  String path = getRelPath() + "uploads\\" + fileName;
  
  // 解決中文文件名的保存名亂碼
  fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
  return new FileInputStream(path);
 }

 public String execute() throws Exception
 {
  return "success";
 }

 public String getRelPath()
 {
  String path = "";
  path = ServletActionContext.getServletContext().getRealPath("/");
  return path;
 }
 /******************getter,setter省略**********************/
}


3.Struts.xml

<action name="downLoad" >
    <result name="success" type="stream">
        <param name="contentType">application/msword</param>
 <param name="inputName">inputStream</param>
 <param name="contentDisposition">attachment;filename="${fileName}"</param>
 <param name="bufferSize">1024</param>
    </result>
</action>

 

我們看到有contentType屬性名,它是用來對文件類型進行限製。

關於contentType的對應表,參見https://blog.csdn.net/woshixuye/article/details/7331632

 

 

 

最後更新:2017-04-02 16:47:43

  上一篇:go Java 筆記03
  下一篇:go Android: ViewPager and Fragments