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

news2024/10/5 14:33:23

前言:这边汇总了一下目前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 {

    @Autowired
    private 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 {

    @Autowired
    private 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 {

    @Autowired
    private 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 {

    @Autowired
    private 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.coloradmin.cn/o/932911.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分布式 - 服务器Nginx:一小时入门系列之 return 指令

文章目录 1. return 指令语法2. return code URL 示例3. return code text 示例4. return URL 示例 1. return 指令语法 return指令用于立即停止当前请求的处理&#xff0c;并返回指定的HTTP状态码和响应头信息&#xff0c;它可以用于在Nginx中生成自定义错误页面&#xff0c;…

分布式事务-seata框架

文章目录 分布式事务0.学习目标1.分布式事务问题1.1.本地事务1.2.分布式事务1.3.演示分布式事务问题 2.理论基础2.1.CAP定理2.1.1.一致性2.1.2.可用性2.1.3.分区容错2.1.4.矛盾 2.2.BASE理论2.3.解决分布式事务的思路 3.初识Seata3.1.Seata的架构3.2.部署TC服务3.3.微服务集成S…

CAPL - Panel和TestModule结合实现测试项可选

目录 一、定义脚本编号和脚本组编号 1、测试组定义 2、测试脚本编号定义

【C++】初步认识模板

&#x1f3d6;️作者&#xff1a;malloc不出对象 ⛺专栏&#xff1a;C的学习之路 &#x1f466;个人简介&#xff1a;一名双非本科院校大二在读的科班编程菜鸟&#xff0c;努力编程只为赶上各位大佬的步伐&#x1f648;&#x1f648; 目录 前言一、泛型编程二、函数模板2.1 函…

Java10(异常处理)

0.复习面向对象 1.异常的体系结构 异常&#xff1a;在Java语言中&#xff0c;将程序执行中发生的不正常情况.(开发中的语法错误和逻辑错误不是异常) 异常事件分两类&#xff08;它们上一级为java.lang.Throwable&#xff09;&#xff1a; Error Java虚拟机无法解决的严重问…

算法通过村第三关-数组黄金笔记|数组难解

文章目录 前言数组中出现超过一半的数字数组中只出现一次的数字颜色的分类问题(荷兰国旗问题)基于冒泡排序的双指针&#xff08;快慢指针&#xff09;基于快排的双指针&#xff08;对撞指针&#xff09; 总结 前言 提示&#xff1a;苦不来自外在环境中的人、事、物&#xff0c;…

最新人工智能源码搭建部署教程/ChatGPT程序源码/AI系统/H5端+微信公众号版本源码

一、AI系统 如何搭建部署人工智能源码、AI创作系统、ChatGPT系统呢&#xff1f;小编这里写一个详细图文教程吧&#xff01; SparkAi使用Nestjs和Vue3框架技术&#xff0c;持续集成AI能力到AIGC系统&#xff01; 1.1 程序核心功能 程序已支持ChatGPT3.5/GPT-4提问、AI绘画、…

Vue3.0极速入门- 目录和文件说明

目录结构 以下文件均为npm create helloworld自动生成的文件目录结构 目录截图 目录说明 目录/文件说明node_modulesnpm 加载的项目依赖模块src这里是我们要开发的目录&#xff0c;基本上要做的事情都在这个目录里assets放置一些图片&#xff0c;如logo等。componentsvue组件…

加快edge网页的下载速度

1、 edge://flags/#enable-parallel-downloading、 2、 点击enabled

Leetcode每日一题:1448. 统计二叉树中好节点的数目(2023.8.25 C++)

目录 1448. 统计二叉树中好节点的数目 题目描述&#xff1a; 实现代码与解析&#xff1a; dfs 原理思路&#xff1a; 1448. 统计二叉树中好节点的数目 题目描述&#xff1a; 给你一棵根为 root 的二叉树&#xff0c;请你返回二叉树中好节点的数目。 「好节点」X 定义为&…

谈谈子网划分的定义、作用、划分方式以及案例

个人主页&#xff1a;insist--个人主页​​​​​​ 本文专栏&#xff1a;网络基础——带你走进网络世界 本专栏会持续更新网络基础知识&#xff0c;希望大家多多支持&#xff0c;让我们一起探索这个神奇而广阔的网络世界。 目录 一、子网划分的定义 二、子网掩码的作用 1、…

[管理与领导-51]:IT基层管理者 - 8项核心技能 - 6 - 流程

前言&#xff1a; 管理者存在的价值就是制定目标&#xff0c;即目标管理、通过团队&#xff08;他人&#xff09;拿到结果。 要想通过他人拿到结果&#xff1a; &#xff08;1&#xff09;目标&#xff1a;制定符合SMART原则的符合业务需求的目标&#xff0c;团队跳一跳就可以…

【mysql是怎样运行的】-EXPLAIN详解

文章目录 1.基本语法2. EXPLAIN各列作用1. table2. id3. select_type4. partitions5. type 1.基本语法 EXPLAIN SELECT select_options #或者 DESCRIBE SELECT select_optionsEXPLAIN 语句输出的各个列的作用如下&#xff1a; 列名描述id在一个大的查询语句中每个SELECT关键…

Unity——后期处理举例

Post Processing&#xff08;后期处理&#xff09;并不属于特效&#xff0c;但现代的特效表现离不开后期处理的支持。本文以眩光&#xff08;Bloom&#xff09;为例&#xff0c;展示一种明亮的激光的制作方法 1、安装后期处理扩展包 较新的Unity版本已经内置了新版的后期处理扩…

2022年03月 C/C++(四级)真题解析#中国电子学会#全国青少年软件编程等级考试

第1题&#xff1a;拦截导弹 某国为了防御敌国的导弹袭击&#xff0c; 发展出一种导弹拦截系统。 但是这种导弹拦截系统有一个缺陷&#xff1a; 虽然它的第一发炮弹能够到达任意的高度&#xff0c;但是以后每一发炮弹都不能高于前一发的高度。 某天&#xff0c; 雷达捕捉到敌国的…

Linux内核学习(十)—— 块 I/O 层(基于Linux 2.6内核)

目录 一、剖析一个块设备 二、缓冲区和缓冲区头 三、bio 结构体 四、请求队列 五、I/O 调度程序 系统中能够随机&#xff08;不需要按顺序&#xff09;访问固定大小数据片&#xff08;chunks&#xff09;的硬件设备称作块设备&#xff0c;这些固定大小的数据片就称作块。最…

项目进度管理(4-1)关键链法

1 关键链法产生的背景 关键链法&#xff08;Critical Chain Method&#xff0c;CCM&#xff09;起源于20世纪80年代&#xff0c;是由Eliyahu M. Goldratt在他的著作《关键链》&#xff08;"Critical Chain"&#xff09;中首次提出和阐述的。Eliyahu M. Goldratt是以…

Java 时间String转Date类型

Testpublic void testTime() throws ParseException {SimpleDateFormat format new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//法一&#xff1a;String time111 "2023-08-14 18:13:10";Date date format.parse(time111);System.out.println("法一…

4.18 TCP 和 UDP 可以使用同一个端口吗?

目录 TCP 和 UDP 可以同时绑定相同的端口吗&#xff1f; 多个 TCP 服务进程可以绑定同一个端口吗&#xff1f; 重启 TCP 服务进程时&#xff0c;为什么会有“Address in use”的报错信息&#xff1f; 重启 TCP 服务进程时&#xff0c;如何避免“Address in use”的报错信息…

Java之API详解之System类的详解

2 System类 2.1 概述 tips&#xff1a;了解内容 查看API文档&#xff0c;我们可以看到API文档中关于System类的定义如下&#xff1a; System类所在包为java.lang包&#xff0c;因此在使用的时候不需要进行导包。并且System类被final修饰了&#xff0c;因此该类是不能被继承的。…