使用GAE + Django将图像上传到Blob

时间:2011-08-22 19:13:03

标签: django google-app-engine image-uploading

我正在使用GAE和Django编写应用程序,我想让用户能够上传他的图像​​。此外,我希望此图像作为blob存储在GAE的数据存储区中。我看过很多例子,但没有特别针对这种情况。虽然,我觉得这是一个普遍的问题。

我想要的只是创造一个新产品,这个新产品必须有一个图像。

第一次尝试:我试图在产品模型中添加一个图像属性(db.BlobProperty()),显然django不会在显示的表单中包含它。

第二次尝试:我创建了一个具有两个属性的新实体(product为db.ReferenceProperty(),image为db.BlobProperty())。有了这个,我尝试与django表单并行工作,修改django HTML表单(包括| input type ='file'name ='img'/ |),期望我可以从请求对象中获取图像,但我再次失败了。

这是产品类:

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 Form(python):

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')

正如您所看到的,请求处理程序基于Google的Gift-Tutorial

所以,如果有人能说出我的意见,我会非常感激!

提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可能希望查看使用blobstore API with blobstoreuploadhandler和/或编辑请求处理程序的示例,将上传的文件存储为blobproperty或blobreference属性,具体取决于您是使用blobstore API还是仅使用blobproperty变量。您可以具体了解http post数据,即`

self.request.post('img').file.read() 我建议您选择blobstore API和blobstoreuploadhandler,因为这会自动为您做一些非常好的事情:1。存储MIM类型和2.存储文件名3.通过get_serving_url启用服务,这有几个优点。

相关问题