简体   繁体   English

使用Django上传图片

[英]image uploading using django

i have an code, code is running well, problem with this code is that it did not get the filename when the file is uploaded. 我有一个代码,代码运行良好,此代码的问题是文件上传时未获取文件名。

views.py views.py

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

        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
        if 'filename' in request.FILES:
            filename = request.FILES['filename']
        else:
           return HttpResponseRedirect('/user_profileform/')
    else:
        form = UploadFileForm()
        return render_to_response('user_profile.html', {'form': form })

def handle_uploaded_file(f):

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

my form is :- 我的表格是:-

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

when using this the file is uploaded properly but did not get the file name,, why. 使用此文件时,文件已正确上传,但未获取文件名,原因。

The issue is probably that you are trying to read the filename from the request.FILES dictionary. 问题可能是您正在尝试从request.FILES字典中读取文件名。 This dictionary contains an UploadedFile object for each file upload field in your form. 该词典包含表单中每个文件上载字段的UploadedFile对象。 The filename is a property of that UploadedFile object. 文件名是该UploadedFile对象的属性。 Try this: 尝试这个:

if request.FILES['file'].name:
    filename = request.FILES['file'].name

If that doesn't work, show us your actual form and the code where you are trying to use the filename. 如果这样不起作用,请向我们显示您的实际格式以及尝试使用文件名的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM