https://blog.csdn.net/stubbornness1219/article/details/72356632

Springboot对资源的描述提供了相应的接口,其主要实现类有ClassPathResource、FileSystemResource、UrlResource、ByteArrayResource、

ServletContextResource和InputStreamResource。

  1. ClassPathResource可用来获取类路径下的资源文件。假设我们有一个资源文件test.txt在类路径下,我们就可以通过给定对应资源文件在类路径下的路径path来获取它,new ClassPathResource(“test.txt”)。
  2. FileSystemResource可用来获取文件系统里面的资源。我们可以通过对应资源文件的文件路径来构建一个FileSystemResource。FileSystemResource还可以往对应的资源文件里面写内容,当然前提是当前资源文件是可写的,这可以通过其isWritable()方法来判断。FileSystemResource对外开放了对应资源文件的输出流,可以通过getOutputStream()方法获取到。
  3. UrlResource可用来代表URL对应的资源,它对URL做了一个简单的封装。通过给定一个URL地址,我们就能构建一个UrlResource。
  4. ByteArrayResource是针对于字节数组封装的资源,它的构建需要一个字节数组。
  5. ServletContextResource是针对于ServletContext封装的资源,用于访问ServletContext环境下的资源。ServletContextResource持有一个ServletContext的引用,其底层是通过ServletContext的getResource()方法和getResourceAsStream()方法来获取资源的。
  6. InputStreamResource是针对于输入流封装的资源,它的构建需要一个输入流。

Resource接口中主要定义有以下方法:

  1. exists():用于判断对应的资源是否真的存在。
  2. isReadable():用于判断对应资源的内容是否可读。需要注意的是当其结果为true的时候,其内容未必真的可读,但如果返回false,则其内容必定不可读。
  3. isOpen():用于判断当前资源是否代表一个已打开的输入流,如果结果为true,则表示当前资源的输入流不可多次读取,而且在读取以后需要对它进行关闭,以防止内存泄露。该方法主要针对于InputStreamResource,实现类中只有它的返回结果为true,其他都为false。
  4. getURL():返回当前资源对应的URL。如果当前资源不能解析为一个URL则会抛出异常。如ByteArrayResource就不能解析为一个URL。
  5. getFile():返回当前资源对应的File。如果当前资源不能以绝对路径解析为一个File则会抛出异常。如ByteArrayResource就不能解析为一个File。
  6. getInputStream():获取当前资源代表的输入流。除了InputStreamResource以外,其它Resource实现类每次调用getInputStream()方法都将返回一个全新的InputStream。
  7. 以及一些类似于Java中的File的接口,比如getName,getContenLength等等。

如果需要获取本地文件系统中的指定路径下的文件,有一下几种方式

  1. 通过ResponseEntity<InputStreamResource>实现
  2. 通过写HttpServletResponse的OutputStream实现

第一种方式通过封装ResponseEntity,将文件流写入body中。这里注意一点,就是文件的格式需要根据具体文件的类型来设置,一般默认为application/octet-stream。文件头中设置缓存,以及文件的名字。文件的名字写入了,都可以避免出现文件随机产生名字,而不能识别的问题。

  1. @RequestMapping(value = "/media", method = RequestMethod.GET)
  2. public ResponseEntity<InputStreamResource> downloadFile( Long id)
  3. throws IOException {
  4. String filePath = "E:/" + id + ".rmvb";
  5. FileSystemResource file = new FileSystemResource(filePath);
  6. HttpHeaders headers = new HttpHeaders();
  7. headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
  8. headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
  9. headers.add("Pragma", "no-cache");
  10. headers.add("Expires", "0");
  11. return ResponseEntity
  12. .ok()
  13. .headers(headers)
  14. .contentLength(file.contentLength())
  15. .contentType(MediaType.parseMediaType("application/octet-stream"))
  16. .body(new InputStreamResource(file.getInputStream()));
  17. }

第二种方式采用了Java中的File文件资源,然后通过写response的输出流,放回文件。

  1. @RequestMapping(value="/media/", method=RequestMethod.GET)
  2. public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) {
  3. // Get your file stream from wherever.
  4. String fullPath = "E:/" + id +".rmvb";
  5. File downloadFile = new File(fullPath);
  6. ServletContext context = request.getServletContext();
  7. // get MIME type of the file
  8. String mimeType = context.getMimeType(fullPath);
  9. if (mimeType == null) {
  10. // set to binary type if MIME mapping not found
  11. mimeType = "application/octet-stream";
  12. System.out.println("context getMimeType is null");
  13. }
  14. System.out.println("MIME type: " + mimeType);
  15. // set content attributes for the response
  16. response.setContentType(mimeType);
  17. response.setContentLength((int) downloadFile.length());
  18. // set headers for the response
  19. String headerKey = "Content-Disposition";
  20. String headerValue = String.format("attachment; filename=\"%s\"",
  21. downloadFile.getName());
  22. response.setHeader(headerKey, headerValue);
  23. // Copy the stream to the response's output stream.
  24. try {
  25. InputStream myStream = new FileInputStream(fullPath);
  26. IOUtils.copy(myStream, response.getOutputStream());
  27. response.flushBuffer();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
    //文件下载相关代码
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "b60bcf72-219d-4e92-88de-ed6b0ad9b0e7-2018-04-23-14-09-14.xls";// 设置文件名,根据业务需要替换成要下载的文件名
if (fileName != null) {
//设置文件路径
String realPath = "D:\\eclipsworksapce1\\upgrade\\src\\main\\webapp\\upload\\tbox\\456789\\";
File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/octet-stream");//
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}

Springboot文件下载的更多相关文章

  1. SpringMVC,SpringBoot文件下载

    前言 最近严查security, 导致原来暴露出去的s3不能用了,不允许public的s3,暂时的折中方案是自己做跳转.于是需要在SpringMVC中实现文件下载功能. 关于文件存储的设计 文件存储通 ...

  2. vue+springboot文件下载

    //vue element-ui <el-button size="medium" type="primary" @click="downloa ...

  3. vue+axios+springboot文件下载

    //前台代码 <el-button size="medium" type="primary" @click="downloadFile" ...

  4. 对Web(Springboot + Vue)实现文件下载功能的改进

    此为 软件开发与创新 课程的作业 对已有项目(非本人)阅读分析 找出软件尚存缺陷 改进其软件做二次开发 整理成一份博客 原项目简介 本篇博客所分析的项目来自于 ジ绯色月下ぎ--vue+axios+sp ...

  5. SpringBoot/SpringMVC文件下载方式

    本篇文章引用外网博客代码,共描述SpringMVC下三种文件下载方式,本人测试在SpringBoot(2.0以上版本)正常使用. 引用博客,强烈推荐https://www.boraji.com. pa ...

  6. SpringBoot之文件下载

    package org.springboot.controller; import org.springboot.constant.Constant; import org.springframewo ...

  7. SpringBoot的文件下载

    SpringBoot的文件下载 2017年11月29日 10:32:20 阅读数:3907 SpringBoot的文件下载方法有很多,此处只记录使用Spring的Resource实现类FileSyst ...

  8. SpringBoot(三):文件下载

    SpringBoot(三):文件下载 2017年08月02日 10:46:42 阅读数:6882 在原来的SpringBoot–uploadfile项目基础上添加文件下载的Controller: @R ...

  9. springBoot中使用使用junit测试文件上传,以及文件下载接口编写

    本篇文章将介绍如何使junit在springBoot中测试文件的上传,首先先阅读如何在springBoot中进行接口测试. 文件上传操作测试代码 import org.junit.Before; im ...

随机推荐

  1. Web前端都学点儿啥?

    Web开发如今是如日中天,热的发烫.但是Web开发相关的技术和知识却像N座大山一样,耸立在我们面前,连绵起伏,漫无边际.那么这些山头那些我们应该占领,那些我们应该绕开,很多人看着就蒙了,这不光是初学者 ...

  2. 个人博客开发之 xadmin 安装

    项目源码下载:http://download.vhosts.cn xadmin 下载地址:https://github.com/sshwsfc/xadmin或 https://github.com/s ...

  3. SecurCRT 远程linux 输入中文及 oracle 查询出文号问题

    一. 首先确认你的linux是否设置了支持中文 cat /etc/sysconfig/i18n 其中: LANG 变量是 language 的简称, 这个变量时决定系统的默认语言, 即系统菜单, 程序 ...

  4. onload 和 onunload 事件

    onload 和 onunload 事件会在用户进入或离开页面时被触发. onload 事件可用于检测访问者的浏览器类型和浏览器版本,并基于这些信息来加载网页的正确版本. onload 和 onunl ...

  5. python django -3 视图

    视图 视图接受Web请求并且返回Web响应 视图就是一个python函数,被定义在views.py中 响应可以是一张网页的HTML内容,一个重定向,一个404错误等等 响应处理过程如下图: URLco ...

  6. 用VS2010进行CMAKE的时候“LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏”

    由于要编译LTP,LTP在MINGW下又不能编译,所以忍痛安装了VS2010+CMAKE. 由于VS在本科时候虐我千百遍,所以一直心存阴影... 转入正题,当cmake的时候, 它提示 “LINK : ...

  7. 基于jQuery表格增加删除代码示例

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. spark hive结合杂记(hive-site.xml)

    1.下载spark源码,在spark源码目录下面有个make-distribution.sh文件,修改里面的参数,使编译后能支持hive,修改后执行该文件.(要预先安装好maven才能编译). 2.将 ...

  9. Introduction to Mathematical Thinking - Week 7

    Q: Why did nineteenth century mathematicians devote time to the proof of self-evident results? Selec ...

  10. IOS开发复习笔记(4)-TableView

    总结几个TableView常用的代码 1.初始化方面 static string CellIndetifier=@"cellIndetifier"; -(NSInteger)num ...