问题
We can think about how serving a list of images works in HTML. When we serve a page it includes tags that reference an image and then the browser makes a separate request to get each one. This works well with mongodb. We can just serve the page and insert tags like
<img src="/profile_pics/userid">
and then our server just redirects that path to the GridFS file with{"profile_pic": userid}
.
Source: http://www.markus-gattol.name/ws/mongodb.html
I have tried:
HTML
<li>
<img src="/static/img/gridfs/download.jpg">
</li>
Bottle Route
# 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
Error
I get a 404 for https://mysite.com/static/img/gridfs/download.jpg
- both when trying to access the image URL directly in a browser, and in the Firebug console error tab when loading the page.
Edit:
Working Code
@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
Note: Using static
instead of another word like gridfs
caused the above not to work. I don't know why. All other routes had been commented out when testing.
回答1:
this works for me. First in the 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')
Then in 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)
When I visit http://localhost:8080/static/img/gridfs/image.jpg
I see my image in the browser.
I notice you put "https://" in the example URL, are you using a Bottle plugin or a frontend server like Apache?
来源:https://stackoverflow.com/questions/21117166/how-to-link-to-an-image-in-gridfs-in-an-img-tag