如何在<img/>标记中链接到GridFS中的图像?

时间:2014-01-14 15:21:33

标签: mongodb python-2.7 bottle gridfs

  

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

来源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之类的其他字词会导致上述情况失效。我不知道为什么。测试时已将所有其他路线注释掉。

1 个答案:

答案 0 :(得分:2)

这对我有用。首先在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时,我在浏览器中看到了我的图片。

我注意到您在示例网址中添加了“https://”,您使用的是Bottle插件还是像Apache这样的前端服务器?

相关问题