SpringBoot上传文件夹

SpringBoot上传文件夹

SpringBoot上传文件夹

前言

个人开发过程中的经验总结

前端

此处以vue3为例

html 复制代码
<template>
  <form @submit.prevent="uploadFiles" ref="form">
    <input
      type="file"
      name="folder"
      ref="folderInput"
      multiple
      webkitdirectory
    />
    <button type="submit">上传</button>
  </form>
</template>

<script setup>
import { ref } from "vue";

const folderInput = ref(null);
const form = ref(null);

const uploadFiles = () => {
  const formData = new FormData(form.value);

  // 发送数据到服务器
  fetch("http://localhost:8080/file/uploadFolder", {
    method: "POST",
    body: formData,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("上传失败");
      }
      return response.json(); // 如果服务器返回JSON格式的响应,可以解析为JSON
    })
    .then((data) => {
      // 处理成功的响应,可以根据需要更新UI或执行其他操作
      console.log("上传成功:", data);
    })
    .catch((error) => {
      // 处理错误
      console.error("上传失败:", error);
    });
};
</script>

后端

FileController

java 复制代码
@RestController
@RequestMapping("/file/")
@CrossOrigin
public class FileController {

    @PostMapping("/uploadFolder")
    public Result uploadFolder(MultipartFile[] folder) {
    	// 指定存放目录
        boolean b = FilesUtil.saveFiles("D:/upload", folder);
        if (b)
            return ResultUtil.success("上传成功");
        else
            return ResultUtil.error("有至少一个文件上传失败");
    }
}

FilesUtil

java 复制代码
public class FilesUtil {

    public static boolean saveFiles(String savePath, MultipartFile[] files) {
        // 检查文件数组是否为空或长度为0,如果是则直接返回false
        if (files == null || files.length == 0) {
            return false;
        }

        // 如果savePath以"/"结尾,去掉末尾的"/"
        if (savePath.endsWith("/")) {
            savePath = savePath.substring(0, savePath.length() - 1);
        }

        boolean allFilesSaved = true; // 用于记录所有文件是否都保存成功

        // 遍历文件数组,保存每个文件
        for (MultipartFile file : files) {
            // 构建文件的完整路径
            String filePath = savePath + "/" + file.getOriginalFilename();
            // 确保目录存在,不存在则创建
            makeDir(filePath);

            // 创建文件对象并保存文件
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
            } catch (IllegalStateException | IOException e) {
                // 记录异常信息,可以考虑使用日志框架
                System.err.println("Failed to save file: " + file.getOriginalFilename());
                e.printStackTrace();
                allFilesSaved = false; // 标记为有文件保存失败
            }
        }

        return allFilesSaved; // 返回是否所有文件都保存成功
    }

    private static void makeDir(String filePath) {
        // 如果filePath中含有"/",则获取目录路径
        int lastIndex = filePath.lastIndexOf('/');
        if (lastIndex > 0) {
            String dirPath = filePath.substring(0, lastIndex);
            File dir = new File(dirPath);
            // 如果目录不存在,则创建目录
            if (!dir.exists() && !dir.mkdirs()) {
                System.err.println("Failed to create directory: " + dirPath);
            }
        }
    }
}
相关推荐
懒虫虫~16 分钟前
基于SpringBoot利用死信队列解决RabbitMQ业务队列故障重试无效场景问题
spring boot·rabbitmq
卑微的Coder2 小时前
Redis Set集合命令、内部编码及应用场景(详细)
java·数据库·redis
CrissChan2 小时前
Pycharm 函数注释
java·前端·pycharm
启航挨踢3 小时前
java学习电子书推荐
java
wgslucky3 小时前
Dubbo报错:module java.base does not “opens java.lang“ to unnamed module
java·开发语言·dubbo
小约翰仓鼠4 小时前
vue3子组件获取并修改父组件的值
前端·javascript·vue.js
Lin Hsüeh-ch'in4 小时前
Vue 学习路线图(从零到实战)
前端·vue.js·学习
DougLiang4 小时前
关于easyexcel动态下拉选问题处理
java·开发语言
mochensage4 小时前
C++信息学竞赛中常用函数的一般用法
java·c++·算法
烛阴5 小时前
bignumber.js深度解析:驾驭任意精度计算的终极武器
前端·javascript·后端