springmvc基础知识(11):下载文件

使用spring提供的 ResponseEntity 进行文件下载

  • 处理方法:
@RequestMapping("/downloadFile.do")
public ResponseEntity<byte[]> downloadFile(String fileName) throws IOException {
     //http请求头
       HttpHeaders headers = new HttpHeaders();
       //设置attachment(附件),让浏览器识别为下载
       headers.add("Content-Disposition", "attachment;filename="+fileName);
       //文件路径
       String downLoadPath = "F:/upload/"+fileName;
       //获取文件流
       InputStream in = new BufferedInputStream(new FileInputStream(downLoadPath)); 
       //将文件读到字节数组中
       byte[] b = new byte[in.available()];
       in.read(b);
       in.close();
       //http状态码也可以使用 HttpStatus.CREATED
       HttpStatus status = HttpStatus.OK;
       ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(b,headers,status);
       return responseEntity;
}
  • 前台:
<a href="downloadFile.do?fileName=img.png">点击下载</a>

原始方式:

@ResponseBody
@RequestMapping("/downloadFile")
public byte[] testDownload(HttpServletResponse response,String fileName) throws IOException{
    //设置请求头,否则浏览器不会识别这是下载
    response.setHeader("Content-Disposition", "attachment;filename="+fileName);
    //文件路径
    String downLoadPath = "F:/upload/"+fileName;
    //获取文件流
    InputStream in = new BufferedInputStream(new FileInputStream(downLoadPath)); 
    //将文件读到字节数组中
    byte[] b = new byte[in.available()];
    in.read(b);
    in.close();
    return b;
}

  • 两种方式都是使用输入输出流实现下载,没什么区别。
  • 重点是要记得设置"Content-Disposition","attachment;filename=web.xml"请求头,浏览器才能认得这是一个下载
  • 无论是哪一种方式,他们都是要将文件读到字节数组中
    第一种方式,使用了ResponseEntity,这是spring封装的响应实体。我们定义好响应信息,然后丢进去就行了。
    第二种方式,文件读到字节数组后,利用@responseBody注解将这个字节数组丢到相应信息的body中。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值