Struts2使用註解方式下載檔案

來源:互聯網
上載者:User

使用Struts2
,很多人都知道怎麼用設定檔的形式實現檔案下載
,但是這樣做,要寫設定檔確實麻煩,那有沒有更方便點的方法呢,有!

使用註解@Annotation的方式就可以省去寫設定檔的步驟,在java代碼
中的Action上加上“檔案下載”的註解即可,具體怎麼加呢!?

我們來看一個例子吧,用例子說話勝過千言萬語。

 

@Results( { @Result(name = "download", type = "stream", params = { "contentType", "application/vnd.ms-excel",
"inputName", "inputStream", "contentDisposition", "attachment;filename=/"${downloadFileName}/"", "bufferSize",
"4096" }) })
public class DownLoad2Action extends ActionSupport{
public static final String DOWNLOAD = "download";
private String fileName;// 初始的通過param指定的檔案名稱屬性
public String getFile() throws Exception{
setFileName("add的.xls");
return “download”;
}

public InputStream getInputStream() throws Exception {
WritableWorkbook workbook = Workbook.createWorkbook(new File("d://a.xls"));
WritableSheet sheet = workbook.createSheet("測試", 0);

Label label = new Label(0, 0, "hello world 從");
sheet.addCell(label);
workbook.write();
workbook.close();
return new FileInputStream(new File("d://a.xls"));
}

/** 提供轉換編碼後的供下載
用的檔案名稱 */

public String getDownloadFileName() {

String downFileName = fileName;
try {
downFileName = new String(downFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downFileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}
}

訪問的URL:down-load2!getFile.action

params 中使用索引值對進行設定:key1,value1,key2,value2.....;對應response相應頭資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.