当前位置: 首页 > news >正文

SpringBoot实现文件上传和下载笔记分享(提供Gitee源码)

前言:这边汇总了一下目前SpringBoot项目当中常见文件上传和下载的功能,一共三种常见的下载方式和一种上传方式,特此做一个笔记分享。

目录

一、pom依赖

二、yml配置文件

三、文件下载

3.1、使用Spring框架提供的下载方式

3.2、通过IOUtils以流的形式下载

3.3、边读边下载

四、文件上传

五、工具类完整代码

六、Gitee源码 

七、总结


一、pom依赖

    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

二、yml配置文件

# Spring配置
spring:# 文件上传servlet:multipart:# 单个文件大小max-file-size: 10MB# 设置总上传的文件大小max-request-size: 20MB
server:port: 9090

三、文件下载

3.1、使用Spring框架提供的下载方式

关键代码:

    /*** 使用Spring框架自带的下载方式* @param filePath* @param fileName* @return*/public ResponseEntity<Resource> download(String filePath,String fileName) throws Exception {fileName = URLEncoder.encode(fileName,"UTF-8");File file = new File(filePath);if(!file.exists()){throw new Exception("文件不存在");}return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=" + fileName ).body(new FileSystemResource(filePath));}

请求层:

@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FileUtil fileUtil;@GetMapping("/spring/download")public ResponseEntity<Resource> download() throws Exception {String filePath = "D:\\1.jpg";String fileName = "Spring框架下载.jpg";return fileUtil.download(filePath,fileName);}}

浏览器输入:http://localhost:9090/file/spring/download 

 

下载完成。 

3.2、通过IOUtils以流的形式下载

关键代码:

    /*** 通过IOUtils以流的形式下载* @param filePath* @param fileName* @param response*/public void download(String filePath , String fileName, HttpServletResponse response) throws Exception {fileName = URLEncoder.encode(fileName,"UTF-8");File file=new File(filePath);if(!file.exists()){throw new Exception("文件不存在");}response.setHeader("Content-disposition","attachment;filename="+ fileName);FileInputStream fileInputStream = new FileInputStream(file);IOUtils.copy(fileInputStream,response.getOutputStream());response.flushBuffer();fileInputStream.close();}

请求层: 

@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FileUtil fileUtil;@GetMapping("/io/download")public void ioDownload(HttpServletResponse response) throws Exception {String filePath = "D:\\1.jpg";String fileName = "IO下载.jpg";fileUtil.download(filePath,fileName,response);}}

浏览器访问:http://localhost:9090/file/io/download

下载成功。 

3.3、边读边下载

关键代码:

    /*** 原始的方法,下载一些小文件,边读边下载的* @param filePath* @param fileName* @param response* @throws Exception*/public void downloadTinyFile(String filePath,String fileName, HttpServletResponse response)throws Exception{File file = new File(filePath);fileName = URLEncoder.encode(fileName, "UTF-8");if(!file.exists()){throw new Exception("文件不存在");}FileInputStream in = new FileInputStream(file);response.setHeader("Content-Disposition", "attachment;filename="+fileName);OutputStream out = response.getOutputStream();byte[] b = new byte[1024];int len = 0;while((len = in.read(b))!=-1){out.write(b, 0, len);}out.flush();out.close();in.close();}

请求层:

@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FileUtil fileUtil;@GetMapping("/tiny/download")public void tinyDownload(HttpServletResponse response) throws Exception {String filePath = "D:\\1.jpg";String fileName = "tiny下载.jpg";fileUtil.downloadTinyFile(filePath,fileName,response);}}

浏览器输入:http://localhost:9090/file/tiny/download 

 

下载成功。

四、文件上传

使用MultipartFile上传文件

    /*** 上传文件* @param multipartFile* @param storagePath* @return* @throws Exception*/public String upload(MultipartFile multipartFile, String storagePath) throws Exception{if (multipartFile.isEmpty()) {throw new Exception("文件不能为空!");}String originalFilename = multipartFile.getOriginalFilename();String newFileName = UUID.randomUUID()+"_"+originalFilename;String filePath = storagePath+newFileName;File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}multipartFile.transferTo(file);return filePath;}

请求层:

@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FileUtil fileUtil;@PostMapping("/multipart/upload")public String download(MultipartFile file) throws Exception {String storagePath = "D:\\";return fileUtil.upload(file,storagePath);}}

使用postman工具测试:

在D盘找到此文件。 

五、工具类完整代码

package com.example.file.utils;import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;/*** 文件工具类* @author HTT*/
@Component
public class FileUtil {/*** 使用Spring框架自带的下载方式* @param filePath* @param fileName* @return*/public ResponseEntity<Resource> download(String filePath,String fileName) throws Exception {fileName = URLEncoder.encode(fileName,"UTF-8");File file = new File(filePath);if(!file.exists()){throw new Exception("文件不存在");}return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=" + fileName ).body(new FileSystemResource(filePath));}/*** 通过IOUtils以流的形式下载* @param filePath* @param fileName* @param response*/public void download(String filePath , String fileName, HttpServletResponse response) throws Exception {fileName = URLEncoder.encode(fileName,"UTF-8");File file=new File(filePath);if(!file.exists()){throw new Exception("文件不存在");}response.setHeader("Content-disposition","attachment;filename="+ fileName);FileInputStream fileInputStream = new FileInputStream(file);IOUtils.copy(fileInputStream,response.getOutputStream());response.flushBuffer();fileInputStream.close();}/*** 原始的方法,下载一些小文件,边读边下载的* @param filePath* @param fileName* @param response* @throws Exception*/public void downloadTinyFile(String filePath,String fileName, HttpServletResponse response)throws Exception{File file = new File(filePath);fileName = URLEncoder.encode(fileName, "UTF-8");if(!file.exists()){throw new Exception("文件不存在");}FileInputStream in = new FileInputStream(file);response.setHeader("Content-Disposition", "attachment;filename="+fileName);OutputStream out = response.getOutputStream();byte[] b = new byte[1024];int len = 0;while((len = in.read(b))!=-1){out.write(b, 0, len);}out.flush();out.close();in.close();}/*** 上传文件* @param multipartFile* @param storagePath* @return* @throws Exception*/public String upload(MultipartFile multipartFile, String storagePath) throws Exception{if (multipartFile.isEmpty()) {throw new Exception("文件不能为空!");}String originalFilename = multipartFile.getOriginalFilename();String newFileName = UUID.randomUUID()+"_"+originalFilename;String filePath = storagePath+newFileName;File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}multipartFile.transferTo(file);return filePath;}}

六、Gitee源码 

码云地址:SpringBoot实现文件上传和下载

七、总结

以上就是SpringBoot实现文件上传和下载功能的笔记,一键复制使用即可。

相关文章:

SpringBoot实现文件上传和下载笔记分享(提供Gitee源码)

前言&#xff1a;这边汇总了一下目前SpringBoot项目当中常见文件上传和下载的功能&#xff0c;一共三种常见的下载方式和一种上传方式&#xff0c;特此做一个笔记分享。 目录 一、pom依赖 二、yml配置文件 三、文件下载 3.1、使用Spring框架提供的下载方式 3.2、通过IOUti…...

Git工作流

实际开发项目使用到的分支: main&#xff1a;生产环境&#xff0c;也就是你们在网上可以下载到的版本&#xff0c;是经过了很多轮测试得到的稳定版本。 release&#xff1a; 开发内部发版&#xff0c;也就是测试环境。 dev&#xff1a;所有的feature都要从dev上checkout。 fea…...

【Git Bash】简明从零教学

目录 Git 的作用官网介绍简明概要 Git 下载链接Git 的初始配置配置用户初始化本地库 Git 状态查询Git 工作机制本地工作机制远端工作机制 Git 的本地管理操作add 将修改添加至暂存区commit 将暂存区提交至本地仓库日志查询版本穿梭 Git 分支查看分支创建与切换分支跨分支修改与…...

【QT5-自我学习-线程qThread练习-两种使用方式-2:通过继承Qobject类-自己实现功能函数方式-基础样例】

【QT5-自我学习-线程qThread练习-两种使用方式-2&#xff1a;通过继承Qobject类-自己实现功能函数方式-基础样例】 1、前言2、实验环境3-1、学习链接-参考文章3-2、先前了解-自我总结&#xff08;1&#xff09;线程处理逻辑事件&#xff0c;不能带有主窗口的事件&#xff08;2&…...

两款开箱即用的Live2d

目录 背景第一款&#xff1a;开箱即用的Live2d在vue项目中使用html页面使用在线预览依赖文件地址配置相关参数成员属性源码 模型下载 第二款&#xff1a;换装模型超多的Live2d在线预览代码示例源码 模型下载 背景 从第一次使用服务器建站已经三年多了&#xff0c;记得那是在2…...

LAMP架构详解+构建LAMP平台之Discuz论坛

LAMP架构详解构建LAMP平台之Discuz论坛 1、LAPM架构简介1.1动态资源与语言1.2LAPM架构得组成1.3LAPM架构说明1.4CGI和astcgi1.4.1CGI1.4.2fastcgi1.4.3CGI和fastcgi比较 2、搭建LAMP平台2.1编译安装apache httpd2.2编译安装mysql2.3编译安装php2.4安装论坛 1、LAPM架构简介 1.…...

如何使用腾讯云服务器搭建网站?新手建站教程

使用腾讯云服务器搭建网站全流程&#xff0c;包括轻量应用服务器和云服务器CVM建站教程&#xff0c;轻量可以使用应用镜像一键建站&#xff0c;云服务器CVM可以通过安装宝塔面板的方式来搭建网站&#xff0c;腾讯云服务器网分享使用腾讯云服务器建站教程&#xff0c;新手站长搭…...

mybatis plus 控制台和日志文件中打印sql配置

1 控制台输出sql 配置mybatis-plus的日志实现类为StdOutImpl&#xff0c;该实现类中打印日志是通过System.out.println(s)的方式来打印日志的 mybatis-plus:configuration:log-impl: org.apache.imbatis.logging.stdout.StdOutImpl2 日志文件中写入sql 日志文件中输入sql需要…...

苍穹外卖总结

前言 1、软件开发流程 瀑布模型需求分析//需求规格说明书、产品原型↓ 设计 //UI设计、数据库设计、接口设计↓编码 //项目代码、单元测试↓ 测试 //测试用例、测试报告↓上线运维 //软件环境安装、配置第一阶段&#xff1a;需求分析需求规格说明书、产品原型一般来说…...

Git 删除已经合并的本地分支

在使用 Git 的开发流程中&#xff0c;经常会创建很多的 Git 分支&#xff0c;包括功能分支&#xff08;features/*&#xff09;、发布分支&#xff08;release/*&#xff09;和 hotfix 分支&#xff08;hotfix/*&#xff09;。在开发了一段时间之后&#xff0c;本地就会有出现很…...

递归算法应用(Python版)

文章目录 递归递归定义递归调用的实现递归应用数列求和任意进制转换汉诺塔探索迷宫找零兑换-递归找零兑换-动态规划 递归可视化简单螺旋图分形树&#xff1a;自相似递归图像谢尔宾斯基三角 分治策略优化问题和贪心策略 递归 递归定义 递归是一种解决问题的方法&#xff0c;其精…...

有什么react进阶的项目推荐的?

前言 整理了一些react相关的项目&#xff0c;可以选择自己需要的练习&#xff0c;希望对你有帮助~ 1.ant-design Star&#xff1a;87.1k 阿里开源的react项目&#xff0c;作为一个UI库&#xff0c;省去重复造轮子的时间 仓库地址&#xff1a;https://github.com/ant-design/…...

基于串口透传模块,单片机无线串口空中下载测试

基于串口透传模块&#xff0c;单片机无线串口空中下载测试 ✨无线串口下载&#xff0c;其本质还是串口下载方式&#xff0c;只不过省去了单片机和ISP上位机工具之间的物理有线连接&#xff0c;中间的数据通过无线串口透传模块进行数据中转&#xff0c;传递到单片机串口上。串口…...

研磨设计模式day11代理模式

目录 场景 代码实现 ​编辑 解析 定义 代理模式调用示意图 代理模式的特点 本质 ​编辑何时选用 场景 我有一个订单类&#xff0c;包含订单数、用户名和商品名&#xff0c;有一个订单接口包含了对订单类的getter和setter 现在有一个需求&#xff0c;a创建的订单只…...

vue2 路由进阶,VueCli 自定义创建项目

一、声明式导航-导航链接 1.需求 实现导航高亮效果 如果使用a标签进行跳转的话&#xff0c;需要给当前跳转的导航加样式&#xff0c;同时要移除上一个a标签的样式&#xff0c;太麻烦&#xff01;&#xff01;&#xff01; 2.解决方案 vue-router 提供了一个全局组件 router…...

《C语言编程环境搭建》工欲善其事 必先利其器

C语言编译器 GCC 系列 GNU编译器套装(英语&#xff1a;GNU Compiler Collection&#xff0c;缩写为GCC)&#xff0c;指一套编程语言编译器&#xff0c;常被认为是跨平台编译器的事实标准。原名是&#xff1a;GNU C语言编译器(GNU C Compiler)。 MinGW 又称mingw32 &#xff0c…...

蓝蓝设计ui设计公司作品案例-中节能现金流抗压测试软件交互及界面设计

中国节能是以节能环保为主业的中央企业。中国节能以生态文明建设为己任&#xff0c;长期致力于让天更蓝、山更绿、水更清&#xff0c;让生活更美好。经过多年发展&#xff0c;中国节能已构建起以节能、环保、清洁能源、健康和节能环保综合服务为主业的41产业格局&#xff0c;成…...

汽车制造业外发文件时 如何阻断泄密风险?

汽车制造业是我国国民经济发展的支柱产业之一&#xff0c;具有产业链长、关联度高、就业面广、消费拉动大等特性。汽车制造行业景气度与宏观经济、居民收入水平和固定资产投资密切相关。 汽车制造业产业链长&#xff0c;关联度高&#xff0c;汽车制造上游行业主要为钢铁、化工…...

怎么对App进行功能测试

测试人员常被看作是bug的寻找者&#xff0c;但你曾想过他们实际是如何开展测试的吗&#xff1f;你是否好奇他们究竟都做些什么&#xff0c;以及他们如何在一个典型的技术项目中体现价值&#xff1f;本文将带你经历测试人员的思维过程&#xff0c;探讨他们测试app时的各种考虑. …...

数字流的秩、单词频率(哈希实现)

题目1&#xff1a;数字流的秩 假设你正在读取一串整数。每隔一段时间&#xff0c;你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。请实现数据结构和算法来支持这些操作&#xff0c;也就是说&#xff1a; 实现 track(int x) 方法&#xff0c;每读入一个数字都会调用该方法…...

python打卡day49

知识点回顾&#xff1a; 通道注意力模块复习空间注意力模块CBAM的定义 作业&#xff1a;尝试对今天的模型检查参数数目&#xff0c;并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

css的定位(position)详解:相对定位 绝对定位 固定定位

在 CSS 中&#xff0c;元素的定位通过 position 属性控制&#xff0c;共有 5 种定位模式&#xff1a;static&#xff08;静态定位&#xff09;、relative&#xff08;相对定位&#xff09;、absolute&#xff08;绝对定位&#xff09;、fixed&#xff08;固定定位&#xff09;和…...

04-初识css

一、css样式引入 1.1.内部样式 <div style"width: 100px;"></div>1.2.外部样式 1.2.1.外部样式1 <style>.aa {width: 100px;} </style> <div class"aa"></div>1.2.2.外部样式2 <!-- rel内表面引入的是style样…...

docker 部署发现spring.profiles.active 问题

报错&#xff1a; org.springframework.boot.context.config.InvalidConfigDataPropertyException: Property spring.profiles.active imported from location class path resource [application-test.yml] is invalid in a profile specific resource [origin: class path re…...

HashMap中的put方法执行流程(流程图)

1 put操作整体流程 HashMap 的 put 操作是其最核心的功能之一。在 JDK 1.8 及以后版本中&#xff0c;其主要逻辑封装在 putVal 这个内部方法中。整个过程大致如下&#xff1a; 初始判断与哈希计算&#xff1a; 首先&#xff0c;putVal 方法会检查当前的 table&#xff08;也就…...

安宝特方案丨船舶智造的“AR+AI+作业标准化管理解决方案”(装配)

船舶制造装配管理现状&#xff1a;装配工作依赖人工经验&#xff0c;装配工人凭借长期实践积累的操作技巧完成零部件组装。企业通常制定了装配作业指导书&#xff0c;但在实际执行中&#xff0c;工人对指导书的理解和遵循程度参差不齐。 船舶装配过程中的挑战与需求 挑战 (1…...

JS设计模式(4):观察者模式

JS设计模式(4):观察者模式 一、引入 在开发中&#xff0c;我们经常会遇到这样的场景&#xff1a;一个对象的状态变化需要自动通知其他对象&#xff0c;比如&#xff1a; 电商平台中&#xff0c;商品库存变化时需要通知所有订阅该商品的用户&#xff1b;新闻网站中&#xff0…...

在Mathematica中实现Newton-Raphson迭代的收敛时间算法(一般三次多项式)

考察一般的三次多项式&#xff0c;以r为参数&#xff1a; p[z_, r_] : z^3 (r - 1) z - r; roots[r_] : z /. Solve[p[z, r] 0, z]&#xff1b; 此多项式的根为&#xff1a; 尽管看起来这个多项式是特殊的&#xff0c;其实一般的三次多项式都是可以通过线性变换化为这个形式…...

Proxmox Mail Gateway安装指南:从零开始配置高效邮件过滤系统

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐&#xff1a;「storms…...