我正在为网站编写一个简单的文件上传器。用户看到一个表单:
<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>
并在提交后,我重定向到此功能:
@csrf_exempt
def upload_file(request):
if request.method == 'POST':
print "arun";
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/user_profileform/')
else:
print "ranjeet"
form = UploadFileForm()
return render_to_response('user_profile.html', {'form': form })
def handle_uploaded_file(f):
destination = open(settings.MEDIA_ROOT, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
当我尝试使用此功能时,我总会得到一个例外:
/ user_profileform /
中的IOError[Errno 21]是一个目录:'/ home / ghrix / ghrixbidding / media / images /'
答案 0 :(得分:1)
因为settings.MEDIA_ROOT是目录。您需要提供句柄的文件名。 最好将Model与FileField一起使用,因为它会自动在媒体中生成唯一的文件名。它在https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/
中描述答案 1 :(得分:1)
您正在尝试打开目录的settings.MEDIA_ROOT
。