Java上传文件工具类

2023-12-20 19:41:26

第一个类getUploadDir获取上传文件的目录,我这里获取的jar运行时的所在的目录,开发时就是项目目录,这样就保证了无论在那个系统下运行该jar包都可以适用。如果没有该目录就创建。

 @SneakyThrows
    public static String getUploadDir() {
        String path = ProjectApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();//这个class是启动类,这里自行修改
        path = URLDecoder.decode(path, StandardCharsets.UTF_8.toString());
        if (System.getProperty("os.name").contains("Windows")) {
            int firstIndex = path.indexOf("/");
            path = path.substring(firstIndex+1);
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
        }
        path = path.replace("target/classes/", "");
        int lastIndex = path.lastIndexOf("/");
        path = path.substring(0,lastIndex);
        String url = path + "/upload";
        File uploadDirectory = new File(url);
        if (!uploadDirectory.exists()) {
            uploadDirectory.mkdir(); // 创建目录
        }
        return url;
    }

  

第二个类上传文件

    public static final String UPLOAD_DIR = getUploadDir();

    @SneakyThrows
    public static String uploadFile(MultipartFile file){
        String filePah = UPLOAD_DIR;
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
//在扩展名限制文件,如果不想限制直接去除即可
        if (isValidFileExtension(fileExtension)) {
            File destFile = new File(filePah + File.separator + originalFilename);
            file.transferTo(destFile);
            String fileUrl = filePah + '\\' + originalFilename;
            return fileUrl;
        } else {
            throw new ProjectException(MessageEnum.PAK_ERR.getCode(),MessageEnum.PAK_ERR.getMessage());
        }
    }

//提取扩展名
    private static String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }
//限制文件
   private static boolean isValidFileExtension(String fileExtensions) {
    List<String> allowedExtensions = Arrays.asList("","");//文件类别
    return Arrays.stream(fileExtensions)
            .allMatch(allowedExtensions::contains);
}
    }

文章来源:https://blog.csdn.net/m0_54140659/article/details/135110093
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。