以下文件上传代码有什么问题.request.FILES ['file']看起来是空的
型号:
from django.db import models
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(label="Your file")
查看:
def index(request):
if request.method == 'POST':
a=request.POST
logging.debug(a["title"])
logging.debug(a["file"])
form = UploadFileForm()
form = UploadFileForm(request.POST, request.FILES)
handle_uploaded_file(request.FILES['file'])
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/Files/')
else:
form = UploadFileForm()
return render_to_response('Files/index.html', {'form': form})
def handle_uploaded_file(f):
logging.debug("here1")
#destination = open('some/file/name.txt', 'wb+')
destination = open('/tmp', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
模板:
<form name="lang" action="/test/" method="post">
<table>
<tr><td>
<b> {{ form.file.label_tag }}</b> {{ form.file}}
</td></tr>
<tr><td>
<input type="hidden" value="title" name="title" id="title" />
<input type="submit" value="Save" id="Save"/>
</td></tr>
</table>
</form>
答案 0 :(得分:7)
您需要在表单上设置enctype
属性:
<form enctype="multipart/form-data" method="post" action="/foo/">