2014-02-12 34 views
0

我正嘗試使用Google App Engine(Python)創建一個Web應用程序,該應用程序允許用戶上傳PDF並稍後查看它們。我已經能夠使用BlobProperty將PDF保存到NDB數據存儲中,但是當我將這些文件從數據庫中拉出時,它們是純文本字符串,帶有奇怪的字符。如何在Python中使用blob文件提供PDF

我已經嘗試過在HTML中使用對象標籤以及PDFObject,但都是爲PDF輸入一個url而不是blob文件。有沒有辦法從我的blob文件直接轉到PDF?如果在頁面上顯示PDF實在太難了,我很樂意提供可下載的鏈接。

class Thing(ndb.Model): 
    blob = ndb.BlobProperty() 

HTML2 = """\ 
    <object data={s} type="application/pdf" width="100%" height="100%"></object> 
    """ 

class MainPage(webapp2.RequestHandler): 
    def get(self): 
     thing_query = Thing.query() 
     things = thing_query.fetch() 

     for thing in things: 
      self.response.write(HTML2.format(s=thing.blob)) 

非常感謝!

+0

你能告訴我們你正在使用的代碼嗎?你是否將Content-Type頭文件設置爲''application/pdf'? – mgilson

+0

上傳我的代碼!如果您有任何想法,請告訴我。 – Site

回答

0

blobstore專爲上傳和下載二進制數據而設計。您可以將其用於PDF。

僅在數據存儲區中存儲blob密鑰(字符串)。上傳處理程序將從enctype =「multipart/form-data」表單中的文件輸入中提取PDF,並將其上傳到BlobStore,並允許您保存該Blobkey。

然後,您可以使用從數據存儲區中的相關模型中提取blobkey的處理程序從blobstore提供PDF。

以下是一些用於上傳和下載的示例處理程序。

class Thing(ndb.Model): 
    blobkey = ndb.StringProperty() 

class UploadBarcodeBG(blobstore_handlers.BlobstoreUploadHandler): 
    def post(self): 
     upload_files = self.get_uploads() 
     if len(upload_files): 
      blob_info = upload_files[0] 
      thing = Thing() 
      if thing and blob_info: 
       thing.blobkey = str(blob_info.key()) 
       thing.put() 
       self.redirect_to("ServeThing", thingkey=thing.key()) 


class ServeThing(blobstore_handlers.BlobstoreDownloadHandler): 
    def get(self, thingkey): 
     thing = Thing.get(thingkey) 
     if thing and thing.blobkey: 
      blob_info = blobstore.BlobInfo.get(thing.blobkey) 
      self.send_blob(blob_info) 
     else: 
      self.error(404) 
相關問題