Spring HTTP下载

(1)HTTP 协议可以在客户端和服务器之间传递任何类型的文件。

  HTTP协议下载文档到客户端时候, 必须通过响应头Content-Type设置文件类型。

  例如: 

    contentType=text/html

    contentType=image/png

    contentType=audio/mpeg

(2)如果需要指定下载名,可以通过响应头 Content-Disposition=attachment;filename="demo.xls"设置下载的文件名,写法如下:

  response.setHeader("Content-Disposition", "attachment;filename="+fileName+".xls");   指支持英文

  如需设置中中文名,要进行中文转码。String fileName = java.net.URLEncoder.encode("泓凯账单信息", "UTF-8");

(3)Spring MVC 的控制器下载支持

  @ResponseBody 注解不仅仅能够处理 JSON 数据, 可以自动处理其他数据:

    • 如果返回值是一个JavaBean对象,就序列化JSON字符串反馈到浏览器
    • 如果是byte[], 就将byte[] 数据填充到Response Body中发送到浏览器, 这时需要与 @RequestMapping配合

(4)案例一:动态生成png图片

  
//produces="image/png" 用于指示响应头中要包含Content-Type=image/png
@RequestMapping(value = "/png.do", produces = "image/png") @ResponseBody public byte[] demo() throws IOException { BufferedImage img = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(img, "png", out); byte[] data = out.toByteArray(); out.close(); return data; }

  案例二:导出Excel文件

//动态生成 Excel 文件:             //excel的文件contentType格式
@RequestMapping(value="excel.do",produces="application/vnd.ms-excel")
@ResponseBody
public byte[] excel(
    HttpServletResponse response)
    throws IOException{

    //指定下载时候的文件名
    response.setHeader(
        "Content-Disposition", 
        "attachment;filename="demo.xls"");

    HSSFWorkbook book=new HSSFWorkbook();
    HSSFSheet sheet = book.createSheet(
            "出勤");
    HSSFRow row = sheet.createRow(0);
    HSSFCell cell = row.createCell(0);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue("Hello World!");

    ByteArrayOutputStream out =
        new ByteArrayOutputStream();
    book.write(out);
    out.close();
    byte[] data = out.toByteArray();
    return data;
}

  

 
原文地址:https://www.cnblogs.com/gangbalei/p/6204376.html