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

springboot文件夹上传,java文件夹上传,第1张

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 {

    
    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);
        }
    }

    
    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





文件夹上传


	


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5685628.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存