我正在使用django和谷歌应用引擎。我正在尝试上传图片。
我做了一个表格
<form enctype="multipart/form-data" action="addImage" method="post">
<p>Title of the Image:
<input type="text" name="title" /></p>
<p>Please select image to upload:
<input type="file" name="img" required="True"/></p>
<p><input type="submit" value="Upload" /></p>
</form>
将其映射到此视图
def addImage(request):
image = Image()
image.title = request.POST.get("title")
img = images.resize(request.POST.get('img'),50,50)
image.blob = db.Blob(img)
image.put()
return HttpResponse('<html><head><meta HTTP-EQUIV="REFRESH" content="2; url=/"></head><body>One item added successfuly </body></html>')
它在调试会话中给我这个错误
Exception Type: NotImageError
Exception Value:Empty image data.
WHY ?????
答案 0 :(得分:0)
我没有使用过Google App Engine,但这是我在纯Django 1.3安装上的方法:
<强> forms.py:强>
from django import forms
from django.forms import fields
class UploadImageForm(forms.Form):
image_file = fields.ImageField()
<强> views.py:强>
from django.shortcuts import render_to_response
from django.template import RequestContext
from NAME_OF_YOUR_APP.forms import UploadImageForm
def addImage(request):
if request.method == 'POST':
upload_image_form = UploadImageForm(data=request.POST, files=request.FILES)
if upload_image_form.is_valid():
image_file = request.cleaned_data['image_file']
# do something with the image...
return ...
else:
upload_image_form = UploadImageForm()
context = {'form':upload_image_form}
return render_to_response('path/to/upload_template.html', context, context_instance=RequestContext(request))
<强> upload_template.html:强>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<table>
<tr>
<td>{{ form.image_file.label_tag }}</td>
<td>{{ form.image_file }}</td>
<td>{% if form.image_file.errors %}{% for error in form.image_file.errors %}{{ error }}{% endfor %}{% endif %}</td>
</tr>
</table>
<input type="submit" value="Submit"/>
</form>
您的模板代码看起来不错(缺少{% csrf_token %}
,我不确定GAE是否需要)。您的视图代码应检查请求是否是POST请求。
在我的示例中,我创建了一个名为UploadImageForm的表单,该表单接受要上传的单个image_file
。逻辑的工作原理如下:
addImage()
运行。由于这是一个GET而不是POST请求,它会创建一个空的UploadImageForm(),并将其呈现在upload_template.html中。addImage()
。答案 1 :(得分:0)
非常简单,
编辑此行:
img = images.resize(request.POST.get('img'),50,50)
这一个:
img = request.FILES['img'].read()
确保您使用的是django 1.2
答案 2 :(得分:0)
试试这个..它对我有用...... :)
def addImage(request):
image = Image()
image.title = request.POST.get("title")
image.blob = db.Blob(str(request.FILES['img']['content']))
image.put()
return HttpResponse('<html><head><meta HTTP-EQUIV="REFRESH" content="2; url=/"></head><body>One item added successfuly </body></html>')