2013-08-16 105 views
0

我正在为网站编写一个简单的文件上传器。用户看到的一种形式:在Django中上传图像

<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() 

当我尝试这个功能的时候,我会永远得到一个异常:

IO错误在/ user_profileform/

[错误21]是一个目录: '/家庭/ ghrix/ghrixbidding /媒体/图片/'

回答

1

您正试图打开settings.MEDIA_ROOT这是目录。

+0

当我尝试这个目的地=打开('/ home/ghrix/ghrixbidding /静态/媒体','wb +')比它将显示: - IOError at/user_profileform/[Errno 21]是一个目录:'/ home/ghrix/ghrixbidding/static/- user2644708 –

+0

谢谢,我做到了:) –

1

因为settings.MEDIA_ROOT是目录。您需要为句柄提供文件名。 最好使用带有FileField的Model,因为它会自动在介质中生成唯一的文件名。它在https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/中有描述

+0

媒体根在settings.py MEDIA_ROOT = '/家/ ghrix/ghrixbidding /媒体/图像/' –

+0

当我尝试此 目的地=开放('/家庭/ ghrix/ghrixbidding /静态/媒体定义”, 'WB +') 比它会显示: - IO错误在/ user_profileform/ [错误21]是一个目录: '/家庭/ ghrix/ghrixbidding /静态/媒体' –