strut2文件下载三部曲:一个流、两个头信息

说明:

①一个流,在Action中需要一个getInputStream()的方法来获取下载的内容,其中inputStream是默认的,他会指示StreamResult获得inputStream属性的getter方法。

②两个头,一个为ContentType:默认rext/plain文件形式。主要作用是根据下载的文件类型进行文件设置,需要的任何MIME可以在tomcat里面的配置文件中找到

另一个头是ContentDisposition:默认inline,直接在网页上打开,我们一般把他设置为attachment,弹出窗口查看下载信息和选择下载路径

以下用导出excel数据表格为例:

一、首先在查询出所需要的数据时,进数据放到session域中

servletActionContext.getRequest().getSession().setAttribute("list",list);

二、在页面设置一个按钮

<a href="${pageContext.request.contextPath}/user_exportXls">导出</a>

三、配置struts.xml文件

<action  name="user_*" method="{1}" class="Action的全类名">

   <result name="exportXlsSUCCESS" type="stream">

        <param name="contentType">application/vnd.ms-excel</param>   <!--excel文件类型-->
       <param name="contentDisposition">attachment;filename=用户数据.xls</param> <!--下载弹窗和下载文件名-->

  </result>

</action>

四、Action类 实现getInputStream方法

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);