首页 > 其他分享 >springboot 获取静态资源文件夹

springboot 获取静态资源文件夹

时间:2024-06-01 09:55:46浏览次数:21  
标签:return String 静态 fileName 文件夹 servletContext new public springboot

@Component
public class StaticResourcePathResolver {

    private final ServletContext servletContext;

    @Autowired
    public StaticResourcePathResolver(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public String getStaticResourcesPath() {
        return (String) servletContext.getRealPath("/");
    }

    public String getUploadPath(){
        return new File(this.getStaticResourcesPath(), "upload").getAbsolutePath();
    }
}

上传文件代码:

    @Override
    public Result upload(MultipartFile file) {
        String fileName = System.currentTimeMillis() + "." + getExtension(Objects.requireNonNull(file.getOriginalFilename()));
        File dest = new File(
                srp.getUploadPath(),
                fileName
        );
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return new Result(false, e.getMessage(), 500);
        }
        Result res = new Result(true, "success " + dest.getAbsolutePath(), 200);
        return res;
    }
// 获取文件后缀名
    private static String getExtension(String fileName) {
        int i = fileName.lastIndexOf('.');
        if (i > 0 && i < fileName.length() - 1) {
            return fileName.substring(i + 1).toLowerCase();
        }
        return fileName;
    }

 

标签:return,String,静态,fileName,文件夹,servletContext,new,public,springboot
From: https://www.cnblogs.com/laremehpe/p/18225570

相关文章