2009-10-24 43 views
5

我試圖使用Django在Google App Engine上的db.BlobProperty字段中上傳並保存調整大小的圖像。使用Django將圖像存儲在App Engine上

我的觀點的相關部分處理該請求如下所示:

image = images.resize(request.POST.get('image'), 100, 100) 
recipe.large_image = db.Blob(image) 
recipe.put() 

這似乎是這將是合乎邏輯的Django相當於例子的文檔:

from google.appengine.api import images 

class Guestbook(webapp.RequestHandler): 
    def post(self): 
    greeting = Greeting() 
    if users.get_current_user(): 
     greeting.author = users.get_current_user() 
    greeting.content = self.request.get("content") 
    avatar = images.resize(self.request.get("img"), 32, 32) 
    greeting.avatar = db.Blob(avatar) 
    greeting.put() 
    self.redirect('/') 

(來源:http://code.google.com/appengine/docs/python/images/usingimages.html#Transform

但是,我不斷收到一個錯誤,說︰NotImageError /空圖像數據。

,並指該行:

image = images.resize(request.POST.get('image'), 100, 100) 

我遇到了麻煩的圖像數據。似乎沒有上傳,但我不明白爲什麼。我的表單具有enctype =「multipart/form-data」等等。我認爲我所指的圖像數據有問題。 「request.POST.get('image')」但我想不出如何引用它。有任何想法嗎?

在此先感謝。

回答

9

經過一些來自「hcalves」的指導,我發現了這個問題。首先,與App Engine捆綁在一起的Django的默認版本是0.96版本,以及框架處理上傳文件的方式從此改變。不過,爲了保持與舊應用程序的兼容性,你必須明確地告訴App Engine上使用Django 1.1這樣的:

from google.appengine.dist import use_library 
use_library('django', '1.1') 

你可以閱讀更多有關in the app engine docs

好了,所以這裏的解決方案:

from google.appengine.api import images 

image = request.FILES['large_image'].read() 
recipe.large_image = db.Blob(images.resize(image, 480)) 
recipe.put() 

然後,從數據存儲再次成爲動態圖像,建立圖像的處理程序是這樣的:

from django.http import HttpResponse, HttpResponseRedirect 

def recipe_image(request,key_name): 
    recipe = Recipe.get_by_key_name(key_name) 

    if recipe.large_image: 
     image = recipe.large_image 
    else: 
     return HttpResponseRedirect("/static/image_not_found.png") 

    #build your response 
    response = HttpResponse(image) 
    # set the content type to png because that's what the Google images api 
    # stores modified images as by default 
    response['Content-Type'] = 'image/png' 
    # set some reasonable cache headers unless you want the image pulled on every request 
    response['Cache-Control'] = 'max-age=7200' 
    return response 
3

您可以通過request.FILES ['field_name']訪問上傳的數據。

http://docs.djangoproject.com/en/dev/topics/http/file-uploads/


閱讀更多關於谷歌的圖像API,在我看來,你應該做這樣的事情:

from google.appengine.api import images 

image = Image(request.FILES['image'].read()) 
image = image.resize(100, 100) 
recipe.large_image = db.Blob(image) 
recipe.put() 

request.FILES [ '形象']閱讀()應該工作,因爲它應該是Django的UploadedFile實例。

+0

感謝您的幫助hcalves ,我一定是做錯了,仍然因爲我改變如下: image = images.resize(request.FILES ['image'],300,200) recipe.large_image = db.Blob(image) recipe。放() 現在我在resize()調用中遇到BadImageError。此外,GAE默認使用django .96。也許我應該嘗試改變? 我也試過做request.FILES ['image']。read()但沒有奏效。它告訴我,「'字典'的對象沒有屬性'讀'」 明天我會繼續搞這個。但是,如果你有更多的建議,我全都聽過。再次感謝。 – 2009-10-24 06:32:55

相關問題