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中。

猜你喜欢

转载自blog.csdn.net/abc997995674/article/details/80417200
今日推荐