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);
            }
        }
    }
}
相关推荐
zb200641204 分钟前
CVE-2024-38819:Spring 框架路径遍历 PoC 漏洞复现
java·后端·spring
uzong12 分钟前
AI Agent 是什么,如何理解它,未来挑战和思考
人工智能·后端·架构
2401_8955213414 分钟前
spring-ai 下载不了依赖spring-ai-openai-spring-boot-starter
java·人工智能·spring
追逐时光者25 分钟前
DotNetGuide突破了10K + Star,一份全面且免费的C#/.NET/.NET Core学习、工作、面试指南知识库!
后端·.net
何仙鸟41 分钟前
GarmageSet下载和处理
java·开发语言
wefly20171 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换
yuweiade1 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
ywf12151 小时前
springboot设置多环境配置文件
java·spring boot·后端
小马爱打代码1 小时前
SpringBoot + 消息生产链路追踪 + 耗时分析:从创建到发送,全链路性能可视化
java·spring boot·后端
小码哥_常1 小时前
MyBatis批量插入:从5分钟到3秒的逆袭之路
后端