Spring MVC将上传的图像显示到外部文件夹中

shi*_*iva 1 jsp spring-mvc image-uploading

我正在使用Spring mvc创建一个图像上传应用程序.我将图像成功保存在外部文件夹中.保存图像的代码如下:

  MultipartFile productImage = product.getProductImage();

        path= Paths.get("/oms/images/"+product.getProductName()+".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);

            }
        }
Run Code Online (Sandbox Code Playgroud)

图像已成功保存到该外部文件夹中.但是当我试图将相同的图像显示到jsp文件中时,我最终得到了这个错误....

http://localhost:8081/oms/images/Ss.jpg Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8081/oms/images/pup.jpg Failed to load resource: the server responded with a status of 404 (Not Found) 
Run Code Online (Sandbox Code Playgroud)

显示图像的代码是这样的......

  <img src="<c:url value="/oms/images/${product.productName}.jpg"/>"/>
Run Code Online (Sandbox Code Playgroud)

我看到了同样问题的一些链接,但大多数问题都是将图像保存到与webapp不同的目录中(显然)!

我错过了什么吗?如何将外部资源添加到Spring?如何将用户添加的上传图像显示到jsp页面?

shi*_*iva 6

上述解决方案对我不起作用.如果我尝试从jsp页面调用@WebServlet("/ FetchFile"),则甚至不会调用@WebServlet("/ FetchFile").我用Google搜索并找到了一个解决方案,在Spring mvc dispatcher-servlet.xml中我们可以通过这种方式添加外部资源:

<mvc:resources mapping="/images/**" location="file:///${fullPath}/oms/images/" />
Run Code Online (Sandbox Code Playgroud)

$ {fullPath} 你应该在这里给出完整的路径:

然后从jsp页面你可以像这样调用jsp文件:

<img src="/images/${product.productName}.jpg" alt="image"/>
Run Code Online (Sandbox Code Playgroud)

整整一天后,我终于得到了解决方案,它对我有用.