【问题标题】:How to load an image using its real path in Grails如何在 Grails 中使用其真实路径加载图像
【发布时间】:2013-08-07 15:57:35
【问题描述】:

我的想法是将用户上传的图像保存在上下文路径之外,如下所示:

D:\somefolder\myWeb\web-app\
D:\somefolder\imagesOutsideContextPath\

代码是下一个(在本地工作):

String path = servletContext.getRealPath("/"); 
String parentFolder = new File(path).getParentFile().getParent();
String imagesFolder = parentFolder + "\\imagesOutsideContextPath";

另一个想法(如果这个在服务器上不起作用)是将图像保存在当前用户的主文件夹中为@HoàngLong suggested me

但我无法从视图中加载图像。我认为this article from official documentation 不适用于此目的。 下一个代码不会加载任何内容:

<img src="D:\\somefolder\\imagesOutsideContextPath\\bestImageEver.jpg" alt="if I don't see this message, I'll be happier">

如何使用真实路径而不是 url 路径来加载这些图像?

【问题讨论】:

    标签: html grails gsp


    【解决方案1】:

    有一个新插件可以让这变得简单,请查看http://grails.org/plugin/img-indirect

    【讨论】:

    • 我认为这通常是最好的解决方案。该插件非常好。我只是选择@SérgioMichels 的答案,因为它更适合我已经编写的代码。
    【解决方案2】:

    创建一个动作

    def profileImage() {
        String profilePicturePath = "${grailsApplication.config.profilePictureDirectoryPath}/${params.id}"
        File file = new File(profilePicturePath)
        response.contentType = URLConnection.guessContentTypeFromName(file.getName())
        response.outputStream << file.bytes
        response.outputStream.flush()
    }
    

    然后在参数中使用图像名称调用此操作,例如:

    <g:img uri="${grailsApplication.config.grails.serverURL}/controller/profileImage/${user?.profilePicture?.fileName}"/>
    

    我已经在我的 config.groovy 文件中声明了图像目录文件,例如:

    profilePictureDirectoryPath = '/opt/CvSurgeon/profileImages'
    

    【讨论】:

      【解决方案3】:

      您可以将src 设置为action。这样,您的用户将不知道您的图像存储在哪里(安全性),您可以轻松更改逻辑以显示它们。

      在操作中,只需获取您的图像并打印字节。 Example here.

      【讨论】:

      • 谢谢!这个解决方案更适合我已经编写的代码。但是所有提出的解决方案都是完全正确的,并且根据具体情况可能会更好。
      【解决方案4】:

      首先感谢您的参考。

      使用真实路径加载图片是不安全的。网络浏览器应该不知道图片是如何保存在服务器上的,因此不知道文件夹结构。

      我的意思是系统应该为你所有的图片使用一个特定的 URL,比如http://your_app/photo/user/{id}。然后到那个 URL,你可以构造一个以 id 作为参数的动作,在你的文件系统中查找照片(当然你必须在配置中存储图片文件夹),然后将照片渲染回来。

      【讨论】:

      • 感谢感谢我! :P 我很欣赏它为什么这样做的澄清:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2013-11-24
      • 1970-01-01
      相关资源
      最近更新 更多