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

上传成功后默认访问路径:

http://localhost:9090/api/upload/1717207097696.png

http://localhost:9090     (主机名 + 端口)
/api                      (如果有 tomcat或nginx 的路径 ,没有则不用理会)
/upload                   (静态资源文件夹的名称)
/1717207097696.png        (文件名)

 

 posted on 2024-06-01 09:39  laremehpe  阅读(207)  评论(0编辑  收藏  举报