springboot文件夹上传,java文件夹上传

文件上传基本都用过,是用的MultipartFile;
文件夹上传用的类,差不多:MultipartFile[]、

工具类:

FolderUtils.java

package com.mods.utils;


import java.io.File;
import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;

public class FolderUtils {

    /**
     * 在basePath下保存上传的文件夹
     *
     * @param basePath  上传后保存的路径(例如C:/)
     * @param files		文件夹
     */
    public static void saveMultiFile(String basePath, MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            return;
        }
        if (basePath.endsWith("/") || basePath.endsWith("\\")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        for (MultipartFile file : files) {
            String filePath = basePath + "/" + file.getOriginalFilename();
            makeDir(filePath);
            File dest = new File(filePath);
            file.transferTo(dest);
        }
    }

    /**
     * 确保目录存在,不存在则创建
     *
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }
}

Controller中的方法

    @ApiOperation("上传文件夹-返回文件夹路径")
    @PostMapping("/upload_folder")
    public String uploadFolder(MultipartFile[] folder) {
        String basePath = filePathProperties.getPubPath() + System.currentTimeMillis() + File.separator;
        try {
            FolderUtils.saveMultiFile(basePath, folder);
        } catch (Exception e) {
            return "error";
        }
        String returnPath = basePath.replace("\\", "/");
       //	if (returnPath.startsWith("D:/")) {		//根据个人需要,把返回的字符串前的盘符删掉
       //     return returnPath.substring(3);
       // }
        return returnPath;
    }

最后可以写一个前端页面用于测试

放在Resource下的static文件夹下,访问方式:端口号后跟 folder.html

folder.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件夹上传</title>
</head>
<body>
	<form action="/common/upload_folder" method="post" enctype="multipart/form-data">
		<!-- html5支持选择文件夹上传 -->
		<input type="file" name="folder" multiple webkitdirectory>
		<button type="submit">上传</button>
	</form>
</body>
</html>
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值