使用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相應頭資訊