strut2文件下載三部曲:一個流、兩個頭信息數組
說明:緩存
①一個流,在Action中須要一個getInputStream()的方法來獲取下載的內容,其中inputStream是默認的,他會指示StreamResult得到inputStream屬性的getter方法。tomcat
②兩個頭,一個爲ContentType:默認rext/plain文件形式。主要做用是根據下載的文件類型進行文件設置,須要的任何MIME能夠在tomcat裏面的配置文件中找到session
另外一個頭是ContentDisposition:默認inline,直接在網頁上打開,咱們通常把他設置爲attachment,彈出窗口查看下載信息和選擇下載路徑app
如下用導出excel數據表格爲例:spa
servletActionContext.getRequest().getSession().setAttribute("list",list);excel
<a href="${pageContext.request.contextPath}/user_exportXls">導出</a>xml
3、配置struts.xml文件內存
<action name="user_*" method="{1}" class="Action的全類名">get
<result name="exportXlsSUCCESS" type="stream">
<param name="contentType">application/vnd.ms-excel</param> <!--excel文件類型-->
<param name="contentDisposition">attachment;filename=用戶數據.xls</param> <!--下載彈窗和下載文件名-->
</result>
</action>
public String exportXls()
{
return "exportXlsSUCCESS";
}
public InputStream getInputStram() throws IOException
{
// 將 userData緩存緩存在Session中的數據 ,生成Excel
List<User> userData = (User) ServletActionContext.getRequest().getSession().getAttribute("User");
// 根據內存的數據生成Excel // 工做薄
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
// 生成一張表sheet (表名爲:用戶數據)
HSSFSheet sheet = hssfWorkbook.createSheet("用戶數據");
// 先寫標題行
HSSFRow headRow = sheet.createRow(0);
// 第一行 (標題行,也叫表頭)
headRow.createCell(0).setCellValue("編號");
headRow.createCell(1).setCellValue("用戶名");
headRow.createCell(2).setCellValue("性別");
headRow.createCell(3).setCellValue("愛好");
headRow.createCell(4).setCellValue("電話號碼");
headRow.createCell(5).setCellValue("住址信息");
..................................等
// 向excel寫數據
for (User user: userData)
{
// 每一個分區一行
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1); // 獲取已經存在的最後一行的行數,在這行下再建立新的行
dataRow.createCell(0).setCellValue(user.getId());
dataRow.createCell(1).setCellValue(user.getUsername());
dataRow.createCell(2).setCellValue(user.getGender());
dataRow.createCell(3).setCellValue(user.getHobby());
dataRow.createCell(4).setCellValue(user.getTelephone());
dataRow.createCell(5).setCellValue(user.getAddr());
.....等
}
// 將數據緩存到字節數組 (知識點)
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
hssfWorkbook.write(arrayOutputStream);
arrayOutputStream.close();
byte[] data = arrayOutputStream.toByteArray();
// 再經過字節數組輸入流讀取數據
return new ByteArrayInputStream(data);
}
//實例化一個字節數組輸出流
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
// 將工做簿的數據寫入到字節數組輸出流中
hssfWorkbook.write(arrayOutputStream);
//將字節數組輸出流關閉
arrayOutputStream.close();
//將字節數組輸出流轉換爲字節流
byte[] data = arrayOutputStream.toByteArray();
// 再經過字節數組輸入流讀取數據
InputStream inputStream = new ByteArrayInputStream(data);