2012-02-11 84 views
2

我用python中的谷歌應用引擎編寫了一個簡單的webapp,允許用戶上傳圖像並將其存儲在某處(現在我只是使用基於教程的blob商店)。使用谷歌應用引擎發送圖像到谷歌雲存儲

現在我想將圖像發送到谷歌雲存儲,但不知道如何做到這一點。打開文件時提供兩種模式:「a」和「r」。據我所知,它們都不適用於二進制流。

如何將圖像發送到谷歌雲存儲?代碼片段或引用會很好。 我打算髮送小音頻樣本以及其他二進制數據。

此外,如果用戶希望刪除圖像,該如何刪除圖像?似乎沒有可用的刪除方法。

回答

4

下面是一個簡單的上傳處理程序,它將寫入上傳到bigstore的blob。請注意,您需要將應用的服務帳戶添加到管理大型存儲分區的團隊帳戶。

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): 
    def post(self): 
    upload_files = self.get_uploads('file') 
    blob_info = upload_files[0] 
    in_file_name = files.blobstore.get_file_name(blob_info.key()) 
    infile = files.open(in_file_name) 
    out_file_name = '/gs/mybucket/' + blob_info.filename 
    outfile = files.gs.create(out_file_name, 
           mime_type = blob_info.content_type) 

    f = files.open(outfile, 'a') 
    chunkSize = 1024 * 1024 
    try: 
     data = infile.read(chunkSize) 
     while data: 
     f.write(data) 
     data = infile.read(chunkSize) 
    finally: 
     infile.close() 
     f.close() 

    files.finalize(outfile) 
+0

感謝您的摘錄。如果我使用這種方法,我還會使用blobstore嗎? – MxyL 2012-02-11 18:45:07

+0

是的,在這個例子中,上傳進入blobstore 1st。 – 2012-02-12 08:07:14

2

雲存儲中的二進制流和文本流沒有區別。您只需將字符串(或字節字符串)寫入在"a"模式下打開的文件。按照說明here

此外,如果您正在從blobstore提供圖片,那麼最好使用get_serving_url()here,儘管這取決於您的應用程序。