上传文件但没有获得文件名

时间:2013-08-23 04:46:55

标签: python django

我有一个代码,它有效,但它没有返回文件的实际名称

Views.py:

def upload_file(request):
    getusername = ''
    getfirstname = ''  
    getemail = ''
    getpassword = ''

    if request.method == 'POST':
        getusername = request.POST['username']
        getfirstname = request.POST['first_name']

def handle_uploaded_file(f):

    destination = open('media/filename', 'wb+')
    for chunk in f.chunks(): filename = form.clean_data['file'].name    
        destination.write(chunk)
        destination.close()
        getemail =  request.POST['email']
        form = UploadFileForm(request.POST, request.FILES)
        filename = request.FILES['file']

def handle_uploaded_file(f):

    destination = open('media/filename', 'wb+')
    for chunk in f.chunks(): 
        destination.write(chunk)
    destination.close()

在forms.py

filename = form.clean_data['file'].name    

1 个答案:

答案 0 :(得分:0)

request.FILES['file'].name

handle_uploaded_file(f) f.name

来源:https://docs.djangoproject.com/en/1.6/topics/http/file-uploads/#handling-uploaded-files

您的来源应与此类似:

def upload_file(request):
    if request.method == 'POST':
        form = YourForm(request.POST, request.FILES)
        if form.is_valid():            
            data = loginForm.cleaned_data
            username = data['username']
            first_name = data['first_name']
            #you can retrieve the filename here
            filename = request.FILES['file'].name            
            handle_uploaded_file(request.FILES['file'])
            #...
            return HttpResponseRedirect('/success/url/')
    else:
        form = YourForm()

    return render_to_response('your.html', {'form': form})

def handle_uploaded_file(f):
    #or here
    filename = f.name
    #...
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)