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);
            }
        }
    }
}
相关推荐
一丝晨光6 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
Front思7 分钟前
vue使用高德地图
javascript·vue.js·ecmascript
天上掉下来个程小白8 分钟前
Stream流的中间方法
java·开发语言·windows
Jay_fearless17 分钟前
Redis SpringBoot项目学习
spring boot·redis
xujinwei_gingko19 分钟前
JAVA基础面试题汇总(持续更新)
java·开发语言
liuyang-neu20 分钟前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
一丝晨光31 分钟前
Java、PHP、ASP、JSP、Kotlin、.NET、Go
java·kotlin·go·php·.net·jsp·asp
罗曼蒂克在消亡35 分钟前
2.3MyBatis——插件机制
java·mybatis·源码学习
_GR1 小时前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
coderWangbuer1 小时前
基于springboot的高校招生系统(含源码+sql+视频导入教程+文档+PPT)
spring boot·后端·sql