Spring MVC图像上传和检索JSP页面中的文件



我正在创建一个Spring MVC Web应用程序,其中我正在从用户上载图像并将其保存在我的驱动器(本地笔记本电脑)中的Project文件夹中,我可以成功地检索它们。

保存我正在使用代码的图像:

MultipartFile productImage = product.getProductImage();
               int Id= productService.addProduct(product);
        path= Paths.get("C:/Users/oms/images/"+Id+".jpg");
        //System.out.println(path.toString());
        if(productImage!=null && !productImage.isEmpty()){
            try {
                productImage.transferTo(new File(path.toString()));
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Product Image Saving Failed ",e);
            }
        }

图像已成功地保存。现在要检索它们,我正在使用该代码:

<mvc:resources mapping="/images/**" location="file:///C:/Users/oms/images/" />

我能够成功检索它们。

但是,此应用程序在本地工作正常,但是如果我在云中部署战争文件,它将无法正常工作,因为没有C drive且没有用户。我尝试使用相对路径将图像保存在项目文件夹中,但都失败了。

我尝试了:

 System.out.println("request.getContextPath()"+request.getContextPath());
  System.out.println("request.getPathInfo()"+request.getPathInfo());
 System.out.println("request.getPathTranslated()"+request.getPathTranslated());
 System.out.println("request.getServletPath()"+request.getServletPath());
 System.out.println("servletContext.getRealPath()"+servletContext.getRealPath("/"));

和所有null except the getRealPAth()

servletContext.getRealPath()C:Usersapache-tomcat-8.0.24webappsROOT

显然我无法将它们保存在WebApps文件夹中,因为重新启动服务器后所有图像都将消失(已删除)。我如何获得将图像保存在项目文件夹中的相对路径,以便当我将此项目部署在云中时,它可以正常工作?

从JSP您无法从服务器的文件系统中检索文件,因此您有两个选择:

  • 将图像存储在可以使用URL访问的文件夹中(例如,在Apache HTDOCS文件夹中)

  • sotre de image进入服务器的文件系统并致电servlet以获取它。

最新更新