期望的行爲如何通過PyMongo和Bottle顯示來自MongoDB數據庫的圖像?
上傳到GridFS的圖像,然後顯示在瀏覽器中(只是爲了讓GridFS的工作原理的想法)。
當前行爲
圖像被上傳到GridFS的集合(I可以通過殼訪問它),然後返回500錯誤。
錯誤
Error: 500 Internal Server Error
Sorry, the requested URL 'https:/mysite.com/form_action_path' caused an error:
表
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="data" />
<input type="submit" value="submit">
</form>
瓶
# relevant libraries
import gridfs
from bottle import response
@route('/upload', method='POST')
def do_upload():
data = request.files.data
name, ext = os.path.splitext(data.filename)
if ext not in ('.png','.jpg','.jpeg'):
return "File extension not allowed."
if data and data.file:
raw = data.file.read()
filename = data.filename
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
fs.put(raw,filename=filename)
# this is the part where I am trying to get the image back out
collection = db.fs.files
cursor = collection.find_one({"filename":"download (1).jpg"})
response.content_type = 'image/jpeg'
return cursor
return "You missed a field."
埃德它:
這在瀏覽器返回的圖像:
# .... same as above
# this is the part where I am trying to get the image back out
thing = fs.get_last_version(filename=filename)
response.content_type = 'image/jpeg'
return thing
我剩下的問題是:
- 爲什麼不能初始代碼工作?
- 我該如何返回圖像,以便它可以在圖像標籤中使用?
- 當圖像正在返回時,究竟是被返回?瀏覽器正在解釋的二進制數據?還有別的嗎?
- 並且圖像是否包含合併的
chunks
fs.chunks
收集文檔的data
字段?
謝謝您的信息。早些時候,我提出了一個關於''標籤實現的更具體的問題。它遵循與上面的建議相同的邏輯,但它爲圖像返回404。這個問題在這裏:http://stackoverflow.com/questions/21117166/how-to-link-to-an-image-in-gridfs-in-an-img-tag – user1063287