Springboot实战:文件上传下载,代码精简(附git源码)

Springboot实战:文件上传下载,代码精简(附git源码),第1张

Springboot文件上传下载demo,附源码下载
    • 简介
    • 1.依赖导入
        • 1.1 pom添加hutool工具依赖
    • 2. 文件上传下载
        • 2.1 FileUtils 工具类封装
        • 2.2 编写controller层代码
    • 3 效果演示
        • 3.1 用postman工具测试上传接口
        • 3.2 文件下载效果
    • 4 源码下载


简介

本博客项目源码地址:

  • 项目源码github地址
  • 项目源码国内gitee地址
1.依赖导入 1.1 pom添加hutool工具依赖
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.7.22version>
        dependency>
2. 文件上传下载 2.1 FileUtils 工具类封装
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;


/**
 * @author lqd
 */
@Slf4j
public class FileUtils {

    /**
     * 保存文件
     * 
     * @param files 文件数组
     * @param path  保存路径
     */
    public static void saveFile(MultipartFile[] files, String path) {
        for (MultipartFile file : files
        ) {
            saveFile(file, path);
        }
    }

    /**
     * 保存文件
     * 
     * @param file 文件
     * @param path 保存路径
     */
    public static void saveFile(MultipartFile file, String path) {
        try {
            // 文件夹不存在则创建
            if (!FileUtil.isDirectory(path)) {
                FileUtil.mkdir(path);
            }
            file.transferTo(new File(path + "/" + file.getOriginalFilename()));
            log.info("文件上传成功--{}", file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败--{}", e.getLocalizedMessage());
        }
    }

    /**
     * 文件下载
     */
    public static void getInputStream(final HttpServletResponse response, String path) {
        File file = new File(path);
        if (!FileUtil.isFile(file)) {
            throw new FileNotFoundException();
        }
        String fileName = file.getName();
        // 清空缓冲区,状态码和响应头(headers)
        response.reset();
        // 设置ContentType,响应内容为二进制数据流,编码为utf-8,此处设定的编码是文件内容的编码
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("content-Type", "application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 实现文件下载
        BufferedInputStream bis = FileUtil.getInputStream(path);
        try {
            // 往响应体中写入数据
            OutputStream os = response.getOutputStream();
            IoUtil.copy(bis, os, IoUtil.DEFAULT_BUFFER_SIZE);
            log.info("{} 文件下载成功", fileName);
        } catch (Exception e) {
            log.error("{} 文件下载失败", fileName);
        }
    }
}

2.2 编写controller层代码
import lombok.extern.slf4j.Slf4j;
import m.links.file.utils.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;


/**
 * @author lqd
 */
@RestController
@RequestMapping("file")
@CrossOrigin(origins = "*")
@Slf4j
public class IoFileController {

    @Value("${file.path}")
    private String path;

    @PostMapping("upload")
    public String uploadFile(@RequestParam("files") MultipartFile[] files) {
        FileUtils.saveFile(files, path);
        return "文件上传成功!";
    }

    @GetMapping(value = "/download", consumes = MediaType.ALL_VALUE)
    public void downloadFile(HttpServletResponse response, String fileName) throws IOException {
        FileUtils.getInputStream(response, path + "/" + fileName);
    }

}
3 效果演示 3.1 用postman工具测试上传接口

3.2 文件下载效果

4 源码下载
  • Springboot开发脚手架,集合各种常用框架使用案例,完善的文档,致力于让开发者快速搭建基础环境并让应用跑起来。
  • 项目源码国内gitee地址
  • 项目源码github地址

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/920022.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存