我有这段代码,代码运行良好,但问题是它在上传文件时没有获取文件名。我的代码是 -
views.py
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
if 'filename' in request.FILES:
filename = request.FILES['filename']
else:
raise Exception('did not get any name')
return HttpResponseRedirect('/user_profileform/')
else:
form = UploadFileForm()
return render_to_response('user_profile.html', {'form': form })
def handle_uploaded_file(f):
destination = open('media/filename', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
形式是: -
<form action="/user_profileform/" method="POST" enctype="multipart/form-data" name="uform" id="userform">{% csrf_token %}
{{form}}
<input type="submit" value="submit" name="usubmit">
</form>
错误是: -
没有得到任何名字
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以通过此
获取文件名filename = form.clean_data['file'].name
clean_data可以在form.is_valid()等于True
之后访问