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);
            }
        }
    }
}
相关推荐
励志码农1 小时前
JavaWeb 30 天入门:第二十三天 —— 监听器(Listener)
java·开发语言·spring boot·学习·servlet
哆啦A梦15881 小时前
[前台小程序] 01 项目初始化
前端·vue.js·uni-app
@小匠1 小时前
Spring Cache 多租户缓存隔离解决方案实践
java·spring·缓存
智码看视界2 小时前
老梁聊全栈系列:(阶段一)架构思维与全局观
java·javascript·架构
黎宇幻生2 小时前
Java全栈学习笔记33
java·笔记·学习
一只小风华~3 小时前
Vue:条件渲染 (Conditional Rendering)
前端·javascript·vue.js·typescript·前端框架
程序员码歌4 小时前
明年35岁了,如何破局?说说心里话
android·前端·后端
橙*^O^*安4 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes
BillKu4 小时前
推荐 Eclipse Temurin 的 OpenJDK
java·ide·eclipse
Morri34 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode