2

我有一个代码,它可以工作,但它不返回文件的实际名称

视图.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    
4

1 回答 1

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)
于 2013-08-23T05:32:39.480 回答