【问题标题】:How to link to an image in GridFS in an <img> tag?如何在 <img> 标签中链接到 GridFS 中的图像?
【发布时间】:2014-02-02 17:25:54
【问题描述】:

我们可以考虑如何在 HTML 中提供图像列表。什么时候我们 提供一个页面,它包含引用图像的标签,然后 浏览器发出单独的请求来获取每个请求。这很好用 与 mongodb。我们可以只提供页面并插入<img src="/profile_pics/userid"> 之类的标签,然后我们的服务器只是重定向它 GridFS 文件的路径为{"profile_pic": userid}

来源http://www.markus-gattol.name/ws/mongodb.html

我试过了:

HTML

<li>
<img src="/static/img/gridfs/download.jpg">
</li>

瓶装路线

# relevant libraries
import gridfs
from bottle import response

@route('/static/img/gridfs/<filename>')
def server_gridfs_img(filename):
  dbname = 'grid_files'
  db = connection[dbname]
  fs = gridfs.GridFS(db)
  thing = fs.get_last_version(filename=filename)
  response.content_type = 'image/jpeg'
  return thing

错误

https://mysite.com/static/img/gridfs/download.jpg 得到 404 - 尝试直接在浏览器中访问图像 URL 时,以及加载页面时在 Firebug 控制台错误选项卡中。

编辑:

工作代码

@route('/gridfs/img/<filename>')
# OR @route('/gridfs/img/<filename:path>')
def server_gridfs_img(filename):
  dbname = 'grid_files'
  db = connection[dbname]
  fs = gridfs.GridFS(db)
  thing = fs.get_last_version(filename=filename)
  response.content_type = 'image/jpeg'
  return thing

注意:使用static 而不是像gridfs 这样的另一个词会导致上述操作无效。我不知道为什么。测试时所有其他路线都已被注释掉。

【问题讨论】:

    标签: mongodb python-2.7 bottle gridfs


    【解决方案1】:

    这对我有用。首先在 Python shell 中:

    >>> import pymongo, gridfs
    >>> db = pymongo.MongoClient().my_gridfs
    >>> # Read a file I have put in the current directory.
    >>> img_contents = open('image.jpg', 'rb').read()
    >>> gridfs.GridFS(db).put(img_contents, filename='image.jpg')
    ObjectId('52d6c182ca1ce955a9d60f57')
    

    然后在 app.py 中:

    import gridfs
    import pymongo
    from bottle import route, run, template, response
    
    connection = pymongo.MongoClient()
    
    @route('/static/img/gridfs/<filename>')
    def gridfs_img(filename):
        dbname = 'my_gridfs'
        db = connection[dbname]
        fs = gridfs.GridFS(db)
        thing = fs.get_last_version(filename=filename)
        response.content_type = 'image/jpeg'
        return thing
    
    run(host='localhost', port=8080)
    

    当我访问http://localhost:8080/static/img/gridfs/image.jpg 时,我在浏览器中看到了我的图像。

    我注意到您在示例 URL 中输入了“https://”,您使用的是 Bottle 插件还是 Apache 之类的前端服务器?

    【讨论】:

    • 为了将http 重定向到https,我正在使用stackoverflow.com/a/20311393/1063287 此处发布的解决方案。
    • 解决方案:我不知道为什么,但是在上下文/static/subdir1/subdir2/&lt;filename&gt; 中使用静态会导致错误。如果我用任何其他词替换 static 就可以了。我在测试时注释掉了所有其他路线。我已将工作代码添加到 OP。
    • 服务器前端有 Nginx 或 Apache 吗?也许它已经有一个“/static”的规则。
    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2022-10-17
    • 1970-01-01
    • 2011-01-27
    • 2011-05-02
    • 2012-07-09
    相关资源
    最近更新 更多