2013-02-09 68 views
1

我試圖上傳一個圖片到create_upload_url()創建的URL,使用默認的BlobstoreUploadHandler處理它,然後用get_serving_url()函數返回一個JSON消息給客戶端。圖像的URL。我的代碼如下:使用BlobstoreUploadHandler處理圖片上傳並返回JSON消息

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): 
    def post(self): 
     response = {} 

     upload_files = self.get_uploads('file') 
     blob_info = upload_files[0] 

     response['error'] = False 
     response['message'] = "Image uploaded." 
     response['image_url'] = images.get_serving_url(blob_info.key()) 

     self.response.headers['Content-Type'] = 'application/json' 
     self.response.out.write(json.dumps(response)) 

app = webapp2.WSGIApplication(
    [('/_ih/upload_handler/', UploadHandler), 
    ], debug=True) 

問題是在客戶端沒有收到響應。 AppEngine日誌在請求中顯示狀態200。當使用閃光燈進行請求時,狀態碼是200,並且沒有響應主體,但是使用HTML5將輸出狀態「(取消)」。我不知道發生了什麼事。從我在互聯網上看到的所有代碼片段都可以發揮作用。請幫忙!謝謝。

回答

2

事實證明,這是一個HTML5跨來源資源共享的問題。您可以通過在響應中添加正確的標頭來解決此問題:

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): 
    def post(self): 
     response = {} 

     upload_files = self.get_uploads('file') 
     blob_info = upload_files[0] 

     response['error'] = False 
     response['message'] = "Image uploaded." 
     response['image_url'] = images.get_serving_url(blob_info.key()) 


     self.response.headers.add_header("Access-Control-Allow-Methods", "POST") 
     self.response.headers.add_header("Access-Control-Allow-Origin", "*") 

     self.response.headers['Content-Type'] = 'application/json' 

     self.response.out.write(json.dumps(response)) 
2

要處理上傳並返回JSON響應,您需要將upload_handler重定向到將返回JSON響應的處理程序。

下面是一個例子:

class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler): 

    def post(self): 
     blob_info = self.get_uploads()[0]  
     self.redirect(self.uri_for("successfulUpload",blob_key = blob_info.key())) 


class SuccessfulUpload(BaseHandler): 

    def get(self, blob_Key): 
     response['error'] = False 
     response['message'] = "Image uploaded." 
     response['image_url'] = images.get_serving_url(blobstore.BlobKey(blob_Key)) 
     self.response.headers['Content-Type'] = 'application/json' 
     self.response.out.write(json.dumps(response)) 
+0

即使這樣做可行,BlobstoreUploadHandler不必再返回重定向。最奇怪的部分是它曾經在另一個項目上工作,我也看到很多人也這樣做。我會嘗試使用較舊的SDK進行測試。 – andrei 2013-02-10 02:39:21

+0

@andrei您是否遇到了開發或在現場的問題? – 2013-02-11 08:16:26

+0

您也可以使用多重繼承:class Uploader(blobstore_handlers.BlobstoreUploadHandler,BaseHandler):並且您不必重定向。 – voscausa 2013-02-11 15:14:16