struts2實現簡單檔案下載功能,struts2檔案下載

來源:互聯網
上載者:User

struts2實現簡單檔案下載功能,struts2檔案下載

Struts2提供了stream結果類型,該結果類型是專門用於支援檔案下載功能的。配置stream類型的結果需要指定以下4個屬性。

  contentType:指定被下載檔案的檔案類型

  inputName:指定被下載檔案的入口輸入資料流

  contentDisposition:指定下載的檔案名稱

  bufferSize:指定下載檔案時的緩衝大小 

struts2檔案下載樣本:

1.處理檔案下載的Action:

/** * Description:Struts2控制檔案下載 * Author: Eleven * Date: 2018/1/24 10:39 */public class FileAction extends ActionSupport{  //該成員變數對應著struts.xml中inputName的值,並為其提供get方法  private InputStream targetFile;  //檔案下載  public String download(){    //指定被下載資源的位置,並返回對應的輸入資料流    String path = "/WEB-INF/images/lib.zip";    //利用getResourceAsStream()將指定檔案轉為對應的輸入資料流    targetFile = ServletActionContext.getServletContext().getResourceAsStream(path);    return SUCCESS;  }  //提供get方法  public InputStream getTargetFile() {    return targetFile;  }}

檔案下載,首先得要有被下載的檔案資源,這裡我將被下載檔案放在了項目的WEB-INF/images的路徑下面,可根據自己的需求來,然後直接用ServletContext提供的getResourceAsStream()方法返回指定檔案對應的輸入資料流。 

2.配置struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC  "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  "http://struts.apache.org/dtds/struts-2.3.dtd"><struts>  <constant name="struts.enable.DynamicMethodInvocation" value="false" />  <constant name="struts.devMode" value="true" />  <package name="default" namespace="/" extends="struts-default">    <action name="file_*" class="eleven.action.FileAction" method="{1}">      <!--檔案下載-->      <!--配置結果類型為stream的結果-->      <result type="stream">        <!--指定下載檔案的檔案類型-->        <param name="contentType">application/zip</param><!--image/jpg-->        <!--指定action中返回被下載檔案的InputStream的名稱-->        <param name="inputName">targetFile</param>        <param name="contentDisposition">filename="aaa.zip"</param>        <!--指定下載檔案的緩衝大小-->        <param name="bufferSize">4096</param>      </result>    </action>  </package></struts>

在瀏覽器地址欄中輸入對應的檔案下載的訪問路徑,如http://localhost:8080/demo/file_download,即可下載檔案了。\

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.