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

news/2024/5/17 15:15:52 标签: spring boot, gitee, 后端, java, spring

前言:这边汇总了一下目前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框架提供的下载方式

关键代码:

java">    /**
     * 使用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));
    }

请求层:

java">@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以流的形式下载

关键代码:

java">    /**
     * 通过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();
    }

请求层: 

java">@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、边读边下载

关键代码:

java">    /**
     * 原始的方法,下载一些小文件,边读边下载的
     * @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();
    }

请求层:

java">@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上传文件

java">    /**
     * 上传文件
     * @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;
    }

请求层:

java">@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盘找到此文件。 

五、工具类完整代码

java">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.niftyadmin.cn/n/4970794.html

相关文章

【高级搜索】双向广搜,A*,IDDFS,IDA *算法总结 (terse版)

一、双向广搜 ​ 双向广搜就是从起点和终点同时往中间搜的一个算法。 ​ 注意事项&#xff1a; ​ 在搜索过程中&#xff0c;同一层次下的顺序应该为&#xff1a;搜完一边所有的当前深度的子节点&#xff0c;在搜索另一边。 ​ 队列使用 ​ &#xff08;1&#xff09;合用…

Debezium日常分享系列之:通知初始快照进度、增量快照技术、信号Topic和状态通知Topic

Debezium日常分享系列之&#xff1a;通知初始快照进度、增量快照技术、信号Topic和状态通知Topic 一、初始快照进度二、实现增量快照三、基于信号Topic实现增量快照状态同步状态通知Topic四、基于信号Topic实现临时阻塞快照 一、初始快照进度 初始快照通知以初始快照的聚合类型…

Linux之systemctl添加服务

文章目录 配置文件nginx配置示例 配置详解UnitServiceInstallnamenode配置示例 配置文件 将服务添加到systemctl管理&#xff0c;需要添加自定义的service文件到/usr/lib/systemd/system/下 nginx配置示例 [Unit] DescriptionThe nginx HTTP and reverse proxy server After…

嵌入式设备应用开发(发现需求和提升价值)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】 很多做技术的同学,都会陷入到技术的窠臼之中。对于如何做具体的产品、实现具体的技术,他们可能很感兴趣。但是做出来的东西做什么用,或者说是有没有竞争力,事实上他们不是很关心…

AI 时代,程序员无需焦虑 | 《服务端开发:技术、方法与实用解决方案》(文末送书福利4.0)

文章目录 &#x1f4cb;前言&#x1f3af;程序员会被 AI 取代么&#xff1f;&#x1f3af;服务端开发尚难被 AI 取代&#x1f3af; 服务端开发何去何从&#xff1f;&#x1f3af;业界首部体系化、全景式解读服务端开发的著作&#x1f4ac;读者对象&#x1f4da;本书优势&#x…

vue页面在table字段后加单位

<el-table-column label"售价" align"center" width"120"><template slot-scope"scope">{{ ${scope.row.price.toFixed(2)} 元 }}</template> </el-table-column><el-table-column label"金重" …

检查Javascript对象数组中是否存在对象值,如果没有向数组添加新对象

需求&#xff1a; 如果我有以下对象数组&#xff1a; [ { id: 1, username: fred }, { id: 2, username: bill }, { id: 2, username: ted } ]有没有办法循环遍历数组&#xff0c;以检查特定的用户名值是否已经存在&#xff0c;如果它什么都不做&#xff0c;但是如果它没有用…

power designer 反向工程过程已中断,原因是某些字符无法通过ANSI-->UTF-16转换进行映射

起因&#xff1a;sqlserver导入sql时报错&#xff0c;一查询是power designer 反向工程过程已中断&#xff0c;原因是。某些字符无法通过ANSI-->UTF-16转换进行映射&#xff08;会导致数据丢失&#xff09; 解决办法&#xff1a; 导入成功