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。文件头中设置缓存,以及文件的名字。文件的名字写入了,都可以避免出现文件随机产生名字,而不能识别的问题。

package com.example.demo;

import java.io.IOException;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController {
@RequestMapping(value = "hello" , method = RequestMethod.GET)
public String sayHi() {
return "Hello World!";
} @RequestMapping(value = "/media", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFile()
throws IOException {
String filePath = "Hello.txt";
FileSystemResource file = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
headers.add("Pragma", "no-cache");
headers.add("Expires", ""); return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
} }

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

package com.example.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController {
@RequestMapping(value = "hello" , method = RequestMethod.GET)
public String sayHi() {
return "Hello World!";
} @RequestMapping(value="/media2", method=RequestMethod.GET)
public void getDownload( HttpServletRequest request, HttpServletResponse response) { // Get your file stream from wherever.
String fullPath = "Hello.txt";
File downloadFile = new File(fullPath); ServletContext context = request.getServletContext(); // get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
System.out.println("context getMimeType is null");
}
System.out.println("MIME type: " + mimeType); // set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length()); // set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
response.setHeader(headerKey, headerValue); // Copy the stream to the response's output stream.
try {
InputStream myStream = new FileInputStream(fullPath);
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
} }

Originate from http://blog.csdn.net/qq415200973/article/details/51149234

Spring boot download file的更多相关文章

  1. Spring Boot Reference Guide

    Spring Boot Reference Guide Authors Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch,  ...

  2. Spring Boot Web 开发@Controller @RestController 使用教程

    在 Spring Boot 中,@Controller 注解是专门用于处理 Http 请求处理的,是以 MVC 为核心的设计思想的控制层.@RestController 则是 @Controller ...

  3. Spring Boot FreeMarker 使用教程

    FreeMarker 跟 Thymeleaf 一样,是一种模板引擎,他可以无缝兼容 FreeMarker 在 Spring Boot 开发者中仍然有着很高的地位. 本章重点内容 编写一个最简单的 Fr ...

  4. Spring Boot Mybatis 使用教程

    Mybatis 在当下互联网开发环境,十分重要.本章主要讲述 Mybatis 如何使用. 从本系列开始,都需要用到 mysql 数据库 和其他一些参考的数据库.请准备相关环节.本章需要以下环境支撑: ...

  5. Spring Boot + Jersey发生FileNotFoundException (No such file or directory)

    我在使用Spring Boot + Jersey 项目,解决了上一篇随笔中的FileNotFoundException,然后又报了一个FileNotFoundException,不过报错信息不一样了 ...

  6. Spring Boot:The field file exceeds its maximum permitted size of 1048576 bytes

    错误信息:The field file exceeds its maximum permitted size of 1048576 bytes原因是因为SpringBoot内嵌tomcat默认所能上传 ...

  7. spring boot tomcat 打本地包成war,通过Tomcat启动时出现问题: ZipException: error in opening zip file

    一个第三方公司提供spring boot 项目,直接启动是ok的, 但是打包成war,通过Tomcat启动,就出现 ZipException: error in opening zip file: 2 ...

  8. [转]Spring Boot修改最大上传文件限制:The field file exceeds its maximum permitted size of 1048576 bytes.

    来源:http://blog.csdn.net/awmw74520/article/details/70230591 SpringBoot做文件上传时出现了The field file exceeds ...

  9. spring boot file上传

    用Spring Boot写读取Excel文件小工具的时候遇到的一些小坑已经填平,复制即可满足普通的文件上传功能POI方面只需一个包,其他通用包工程中一般都会带TIPS:前端为了扩展我用ajax异步请求 ...

随机推荐

  1. SAS 9.4 的sid问题解决方案汇总(头疼...)

    每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 因为经常出现sid出现问题,所以问题很多.最常 ...

  2. FFMPEG 实现 YUV,RGB各种图像原始数据之间的转换(swscale)

    FFMPEG中的swscale提供了视频原始数据(YUV420,YUV422,YUV444,RGB24...)之间的转换,分辨率变换等操作,使用起来十分方便,在这里记录一下它的用法. swscale主 ...

  3. Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传

    先上几张图更直观展示一下要实现的功能,本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2 ...

  4. 【原】Java学习笔记031 - 常用类

    package cn.temptation; public class Sample01 { public static void main(String[] args) { /* * 类 Math: ...

  5. 芝麻HTTP:TensorFlow LSTM MNIST分类

    本节来介绍一下使用 RNN 的 LSTM 来做 MNIST 分类的方法,RNN 相比 CNN 来说,速度可能会慢,但可以节省更多的内存空间. 初始化 首先我们可以先初始化一些变量,如学习率.节点单元数 ...

  6. 芝麻HTTP:在阿里云上测试Gerapy教程

    1.配置环境 阿里云的版本是2.7.5,所以用pyenv新安装了一个3.6.4的环境,安装后使用pyenv global 3.6.4即可使用3.6.4的环境,我个人比较喜欢这样,切换自如,互不影响. ...

  7. 【BZOJ3670】动物园(KMP算法)

    [BZOJ3670]动物园(KMP算法) 题面 BZOJ 题解 神TM阅读理解题 看完题目之后 想暴力: 搞个倍增数组来跳\(next\) 每次暴跳\(next\) 复杂度\(O(Tnlogn)\) ...

  8. 【HAOI2015】树上操作(树链剖分)

    题面 Description 有一棵点数为N的树,以点1为根,且树点有边权.然后有M个操作,分为三种: 操作1:把某个节点x的点权增加a. 操作2:把某个节点x为根的子树中所有点的点权都增加a. 操作 ...

  9. jxl 导出数据到excel

    优点: Jxl对中文支持非常好,操作简单,方法看名知意. Jxl是纯javaAPI,在跨平台上表现的非常完美,代码可以再windows或者Linux上运行而无需重新编写 支持Excel 95-2000 ...

  10. iOS开发——下载器的功能基本实现

    今天,做了一个下载器的Demo,即从本地配置的Apache服务器上,下载指定的文件.这次,我们下载服务器根目录下的html.mp4文件. 按照惯例,我们先创建一个URL对象和请求. NSURL *ur ...