2011-08-22 31 views
0

我正在使用GAE和Django編寫一個應用程序,在該應用程序中,我想讓用戶能夠上傳他的圖像​​。另外,我希望這個圖像作爲blob存儲在GAE的數據存儲中。我看過很多例子,但沒有特定於這種情況。雖然,我覺得這是一個普遍的問題。使用GAE + Django將圖像上傳到Blob

我想要的就是創建一個新產品,這個新產品必須有一個圖像。

1日嘗試:我嘗試添加在產品的模型圖像屬性(db.BlobProperty()),顯然Django不包括它的呈現形式。

第二次嘗試:我已經創建了一個具有兩個屬性(產品爲db.ReferenceProperty()和圖像爲db.BlobProperty())的新實體。有了這個,我試圖與修改django HTML表單(包括| input type ='file'name ='img'/ |)的django表單一起工作,期待我可以從請求對象中獲取圖像,但我再次失敗。

這是產品類別:

class Product(db.Model): 
    id = db.IntegerProperty() 
    desc = db.StringProperty() 
    prodCateg = db.ReferenceProperty(ProductCategory) 
    price = db.FloatProperty() 
    details = db.StringProperty() 
    image = db.BlobProperty() 

這是Django表單(HTML):

<form action="{%url admin.editProduct product.key.id%}" enctype="multipart/form-data" method="post"> 
<table> 
{{form}} 
<tr><td><input type="file" name="img" /></td></tr> 
<tr><td><input type="submit" value="Create or Edit Product"></td></tr> 
</table> 
</form> 

這是Django表單(蟒):

class ProductForm(djangoforms.ModelForm): 
    class Meta: 
    model = Product 
    exclude = ['id'] 

這是請求處理程序:

def editProduct(request, product_id): 
    user = users.GetCurrentUser() 
    #if user is None: 
    # return http.HttpResponseForbidden('You must be signed in to add or edit a gift') 

    product = None 
    if product_id: 
    product = Product.get(db.Key.from_path(Product.kind(), int(product_id))) 
    if product is None: 
     return http.HttpResponseNotFound('No product exists with that key (%r)' % 
             product) 

    form = ProductForm(data=request.POST or None, instance=product) 

    ########################## 
    # Ambitious undertaking! # 
    ########################## 
    #if not product_id: 
    # uploadedImage = get("img") 
    # photo = Image() 
    # photo.product = product 
    # uploadedPhoto = request.FILES['img'].read() 
    # photo.image = db.Blob(uploadedPhoto) 
    # image.put() 

    if not request.POST: 
    return respond(request, user, 'addprod', {'form': form, 'product': product}) 

    errors = form.errors 
    if not errors: 
    try: 
     product = form.save(commit=False) 
    except ValueError, err: 
     errors['__all__'] = unicode(err) 
    if errors: 
    return respond(request, user, 'addprod', {'form': form, 'product': product}) 

    product.put() 

    return http.HttpResponseRedirect('/product') 

正如你所看到的請求處理程序是基於谷歌的禮品教程

因此,如果任何人都可以把自己的意見,我會非常感激!

預先感謝您!

回答

0

您可能想要看看使用blobstore API with blobstoreuploadhandler和/或編輯您的請求處理程序將上傳的文件存儲爲blobproperty或blobreferenceproperty的示例,具體取決於您是使用blobstore API還是僅使用blobproperty變量。你可以具體談談HTTP POST數據,即`

self.request.post('img').file.read() 我建議您選擇Blob存儲區API和blobstoreuploadhandler,因爲它會自動做一些非常好的東西你:1.存儲MIM型和2名保存3 。通過get_serving_url啓用服務有幾個優點。