【问题标题】:How to get Project Path in a Java Spring Web App如何在 Java Spring Web App 中获取项目路径
【发布时间】:2018-12-07 18:23:58
【问题描述】:

这是我的项目结构:

Spring web App Structure

如您所见,我有图片文件夹,我需要在其中传输产品图片。但接下来的代码行:

MultipartFile productImage = newProduct.getProductImage();
    String rootDirectory = request.getSession().getServletContext().getRealPath("/");
    if(productImage != null && !productImage.isEmpty())
    {
        try
        {
            productImage.transferTo(new File(rootDirectory + "resources\\images\\" + newProduct.getProductId() + ".png"));

        }
        catch(Exception ex)
        {
            throw new RuntimeException("Product Image Saving failed", ex);
        }
    }

添加新产品后,产品图片上传到: C:\Users\PC\sts_ws\spring-java-app\module2\1\webstore\target\webstore-1.0-SNAPSHOT\resources\images

但我需要路径: C:\Users\PC\sts_ws\spring-java-app\module2\1\webstore\src\main\webapp\resources\images

我不知道如何指向我想要的路径。

感谢您的帮助。

【问题讨论】:

  • 试试看:Paths.get(this.getClass().getClassLoader().getResource("xyz/file.extension").toURI())

标签: java web


【解决方案1】:

你可以这样做,

ClassLoader resource = this.getClass().getClassLoader();
URL path = this.getClass().getResource("/resources/THEPATH ".png");

如果你想得到它,你可以使用它,

File file = new File(path.getFile());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-24
    • 2019-04-21
    • 2015-03-20
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多