当前位置: 首页 > 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实现文件上传和下载功能的笔记,一键复制使用即可。

http://www.lryc.cn/news/142170.html

相关文章:

  • Git工作流
  • 【Git Bash】简明从零教学
  • 【QT5-自我学习-线程qThread练习-两种使用方式-2:通过继承Qobject类-自己实现功能函数方式-基础样例】
  • 两款开箱即用的Live2d
  • LAMP架构详解+构建LAMP平台之Discuz论坛
  • 如何使用腾讯云服务器搭建网站?新手建站教程
  • mybatis plus 控制台和日志文件中打印sql配置
  • 苍穹外卖总结
  • Git 删除已经合并的本地分支
  • 递归算法应用(Python版)
  • 有什么react进阶的项目推荐的?
  • 基于串口透传模块,单片机无线串口空中下载测试
  • 研磨设计模式day11代理模式
  • vue2 路由进阶,VueCli 自定义创建项目
  • 《C语言编程环境搭建》工欲善其事 必先利其器
  • 蓝蓝设计ui设计公司作品案例-中节能现金流抗压测试软件交互及界面设计
  • 汽车制造业外发文件时 如何阻断泄密风险?
  • 怎么对App进行功能测试
  • 数字流的秩、单词频率(哈希实现)
  • 【洛谷】P2678 跳石头
  • Elasticsearch配置优化
  • Springboot整合minio组件-分布式文件存储
  • 多态/虚函数/虚函数表
  • QT中按钮的基类QAbstractButton
  • 并查集(种类并查集,带权并查集)
  • 飞天使-k8s基础组件分析-控制器
  • 有序充电运营管理平台是基于物联网和大数据技术的充电设施管理系统-安科瑞黄安南
  • LeetCode-227-基本计算器Ⅱ
  • dart 学习列表 List
  • 数据结构--树4.2.1(二叉树)