[英]uploading image in django
I'm writing a simple file uploader for a website. 我正在为一个网站写一个简单的文件上传器。 The user sees a form:
用户看到一个表单:
<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>
and upon submit, I redirect to this function: 并在提交后,我重定向到此功能:
@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()
When I try this functionality out, I'll always get an exception: 当我尝试这个功能时,我总会得到一个例外:
IOError at /user_profileform/ / user_profileform /的IOError
[Errno 21] Is a directory: '/home/ghrix/ghrixbidding/media/images/' [Errno 21]是一个目录:'/ home / ghrix / ghrixbidding / media / images /'
Because settings.MEDIA_ROOT is directory. 因为settings.MEDIA_ROOT是目录。 You need to provide filename for handle.
您需要提供句柄的文件名。 Is better to use Model with FileField, because it generates unique file name in media automatically.
最好将Model与FileField一起使用,因为它会自动在媒体中生成唯一的文件名。 It is described in https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/
它在https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/中描述
您正在尝试打开settings.MEDIA_ROOT
这是目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.