一 前言

本文实现的文件下载是使用Apache 的 commons-fileupload 实现;在之前的springboot系列文件中已经讲述过如何实现多文件上传;这篇文件实现的文件下载功能主要是能在浏览器在线预览或者下载至本地;

二 pom依赖

	<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

三 文件下载示例

参数 path 表示相对于根路径的相对路径

参数userAgent 是为了兼容IE判断,如果使用谷歌,火狐浏览器就可以省略这个参数;

参数 filename 表示你下载至本地的文件名;

参数 inline表示是否要在线浏览,true是,false否;

/**
* @Author lsc
* @Description <p> 文件下载</p>
* @Date 2019/11/20 11:54
*/
@RestController
@RequestMapping("file")
public class DownloadController {
// 下载文件的根路径
private String downloadPath = "C:\\mydata\\generator"; @GetMapping("download")
public ResponseEntity<byte[]> downlaodFile(HttpServletRequest request, @RequestParam("path") String path
, @RequestHeader("user-agent") String userAgent, @RequestParam("filename") String filename
,@RequestParam(required = false,defaultValue = "false") boolean inline ) {
// 根路径加上传参数的路径构成文件路径地址
String realPath = downloadPath + path;
File file = new File(realPath);
// 构建响应
ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok();
bodyBuilder.contentLength(file.length());
// 二进制数据流
bodyBuilder.contentType(MediaType.APPLICATION_OCTET_STREAM);
// 文件名编码
try {
String encodeFileName = URLEncoder.encode(filename, "UTF-8");
// IE
if (userAgent.indexOf("MSIE")>0){
bodyBuilder.header("Content-Disposition","attachment;filename="+encodeFileName);
}else {
// 其他浏览器
if (inline){
// 在浏览器中打开
URL url = new URL("file:///" + file);
bodyBuilder.header("Content-Type",url.openConnection().getContentType());
bodyBuilder.header("Content-Disposition","inline;filename*=UTF-8''"+encodeFileName);
}else {
// 直接下载
bodyBuilder.header("Content-Disposition","attachment;filename*=UTF-8''"+encodeFileName);
} }
// 下载成功返回二进制流
return bodyBuilder.body(FileUtils.readFileToByteArray(file));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
// 下载失败直接返回错误的请求
return (ResponseEntity<byte[]>) ResponseEntity.badRequest(); } }

四 tomcat配置

主要是开发特殊字符斜杆,如果是在linux上开发,那就自定义路径,这个步骤可以省略;

@Configuration
public class ServerConfig { //Url路径添加支持字符
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
//设置Tomcate 支持
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
connector.setProperty("relaxedQueryChars", "\\");
}
});
return factory;
} }

五 浏览器测试

下载路径

http://localhost:8080/file/download?path=\2019\11\c7ed67a6-5502-479b-8934-736021426236.jpg&filename=5555.jpg

生成结果

六 源码

github : youku1327

springboot-实现文件下载的更多相关文章

  1. SpringBoot的文件下载

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

  2. SpringBoot/SpringMVC文件下载方式

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

  3. SpringBoot之文件下载

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

  4. 用Springboot实现文件下载功能

    ApiOperation(value = "下载文件", httpMethod = "GET", notes = "downloadFile" ...

  5. SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)

    SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...

  6. vue下载文件

    import fileDownload from 'js-file-download' let params = { ", ", "filename":&quo ...

  7. SpringBoot(三):文件下载

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

  8. Springboot文件下载

    https://blog.csdn.net/stubbornness1219/article/details/72356632 Springboot对资源的描述提供了相应的接口,其主要实现类有Clas ...

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

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

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

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

随机推荐

  1. AtCoder Regular Contest 060

    C - 高橋君とカード / Tak and Cards 思路:dp,先说说我想的,我写的dp数组是dp[i][j][k],表示从前i个数字中,选择j个数字,平均值为k,则dp[i][j][k] = d ...

  2. day1-初识Python之变量

    1.python安装与环境配置 1.1.Windows下的python解释器安装 打开官网 https://www.python.org/downloads/windows/ 下载中心 测试安装是否成 ...

  3. H3C 各种视图之间的关系

  4. 最适合 Python 入门的资源有哪些?

    https://blog.csdn.net/zV3e189oS5c0tSknrBCL/article/details/81230593 学习任何一门编程语言或者技能基本上都遵循3个步骤,第一步是看,第 ...

  5. HTML5--语法

    一.标记方法 1.内容类型(ContentType)还是.text/html 2.声明:<!DOCTYPE html SYSTEM “about:legacy-compat”> 3.字符编 ...

  6. Tenka1 Programmer Beginner Contest D IntegerotS(补)

    当时没做出来,官方题解没看懂,就看别人提交的代码,刚对着别人代码调了几组数据,才发现,思路差不多,不过,原来是这样实现啊,果然我还是很菜 思路:题目要求是选取的这些数字全部进行OR运算,结果<= ...

  7. PL/SQL语言的学习笔记

    一.PL/SQL简介1.什么是PL/SQL程序?(PL/SQL是对SQL语言的一个扩展,从而形成的一个语言) 2.PL/SQL语言的特点(操作Orcale数据库效率最高的就是PL/SQL语言,而不是C ...

  8. HDU 2546 01背包问题

    这里5元是个什么意思呢.差不多就是特殊情况了. 就是说最贵的那个东西先不买.并且最后要留下5元去买那个最贵的. 也就是说对现在金钱-5 拿剩下的钱去对减去最贵的商品后的商品dp.看这些剩下的钱能买多少 ...

  9. 用复制方式创建表 Create Table tbname as select * from user.tab where ...

    用复制方式创建表 Create Table tbname as select * from user.tab where ...

  10. C# AddRange 添加位置

    有没人想知道, AddRange 添加位置 是哪? 是添加到数组的开始,还是数组的末尾? 假如有一个 代码,看起来是下面的,很简单,把一个 list b 放进list a List<int> ...