2014-01-13 19 views
1

期望的行爲如何通過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 

我剩下的問題是:

  • 爲什麼不能初始代碼工作?
  • 我該如何返回圖像,以便它可以在圖像標籤中使用?
  • 當圖像正在返回時,究竟被返回?瀏覽器正在解釋的二進制數據?還有別的嗎?
  • 並且圖像是否包含合併的chunksfs.chunks收集文檔的data字段?

回答

0

最初的代碼不起作用,因爲您要返回PyMongo表示爲Python字典的文檔。 Flask不知道該如何處理它。 (注意,find_one()返回單個文檔,而find()返回一個光標。)

您的最終代碼返回從GridFS.get_last_version()獲取的「thing」,這是一個GridOut對象,用於從GridFS文件。

GridOut是可迭代的:迭代GridOut獲取大塊的腳本。 Flask 確實如此知道如何將一個迭代器變成一個HTTP響應,所以你的代碼的第二個版本可以工作。

課程是:當你想與GridFS交互時,使用GridFS類而不是find()或find_one()。

是的,圖像由fs.chunks集合中的chunks合併後的數據組成。

爲了在一個<img>標籤的形象,這樣的事情應該工作:

@route('/images/<filename>') 
def image(filename): 
    fs = gridfs.GridFS(db) 
    gridout = fs.get_last_version(filename=filename) 
    response.content_type = 'image/jpeg' 
    return gridout 

然後在你的HTML,<img src="/images/filename.jpg">

+0

謝謝您的信息。早些時候,我提出了一個關於''標籤實現的更具體的問題。它遵循與上面的建議相同的邏輯,但它爲圖像返回404。這個問題在這裏:http://stackoverflow.com/questions/21117166/how-to-link-to-an-image-in-gridfs-in-an-img-tag – user1063287

相關問題