1

我尝试使用此代码保存图像。它将图像保存在给定路径,但不获取文件名。我怎么才能得到它?

@csrf_exempt
def upload_file(request):
    if request.method == 'POST':

        form = UploadFileForm(request.POST, request.FILES)

    if 'filename'  in request.FILES:
        filename = request.FILES['filename'].name
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/user_profileform/')
    else:

        form = UploadFileForm()
    return render_to_response('user_profile.html', {'form': form })

def handle_uploaded_file(f):

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

2 回答 2

1

看来您想重用文件名来保存文件,您可以尝试:

def handle_uploaded_file(f):
    filename = f.name  # get the name here
    destination = open('media/'+filename, 'wb+')
    for chunk in f.chunks(): 
        destination.write(chunk)
    destination.close()

在你upload_file看来,也有问题:

@csrf_exempt
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)

    if 'filename'  in request.FILES:
        # filename = request.FILES['filename'].name  # remove this line, you don't need it
        if form.is_valid():
            handle_uploaded_file(request.FILES['filename']) # should be filename here
    #.... your code ....

希望能帮助到你。

于 2013-08-16T08:29:25.067 回答
0

可能是编码错误。您的 POST 是否编码为 UTF-8?这意味着在 HTML 中有类似的内容:

<meta charset="UTF-8" />
于 2013-08-16T05:49:48.183 回答