Django form form upload file

Keywords: Python Django Fragment Attribute

File upload of Django's form form

When generating input tags, you can specify the type of input tag as file type

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4>{{ error_message }}</h4>
<form action="/index/" method="post">
    {% csrf_token %}
    <p><input type="file" name="up_file"></p>
    <input type="submit">
</form>
</body>
</html>

At this time, the page on the web page is as follows

If the user name and password are submitted on the web page, they will be sent to the server through the key value pair.

A set of key values represents a label and its corresponding values.

Select a picture on the web page, submit it by post, and print it on the server request.POST

def index(request):
    if request.method=="POST":
        print(request.POST)
    
    return render(request,"index.html",locals())

The printed information is as follows:

<QueryDict: {'csrfmiddlewaretoken': ['opmSmENIrgdGJJN'], 'up_file': ['1.png']}>

The submitted file name is also in the dictionary. Take out the file name

def index(request):
    if request.method=="POST":
        print(request.POST.get("up_file"))
        print(type(request.POST.get("up_file")))
    
    return render(request,"index.html",locals())

The printing results are as follows:

1.png
<class 'str'>

What you want to get out is the uploaded file, but what you want to get out is the file name of the uploaded file

It can be seen that the uploaded file is not with the data submitted by the form form

Because the size of the uploaded file is usually large, Django will place the uploaded file in a specific folder by default

Printing request.FILES Information about

def index(request):
    if request.method=="POST":
        print(request.POST.get("up_file"))
        print(type(request.POST.get("up_file")))
        print("files:",request.FILES)
    
    return render(request,"index.html",locals())

The results are as follows

1.png
<class 'str'>
files: <MultiValueDict: {}>

request.FILES The result of printing is an empty dictionary. The problem lies in the way of uploading files

Because when uploading files, binary data is transmitted between client and server, which is different from string data.

Binary data transmission, whether in a form or in Ajax, has its own way of transmission.

In the form form, you need to use the method of fragment transfer when uploading files.

modify index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h4>{{ error_message }}</h4>
    <form action="/index/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <p><input type="file" name="up_file"></p>
        <input type="submit">
    </form>
</body>
</html>

Upload the file again and print the information on the server as follows

None
<class 'NoneType'>
files: <MultiValueDict: {'up_file': [<InMemoryUploadedFile: 1.png (image/png)>]}>

According to the printing results, request.FILES You can see the uploaded file in

The print result is a dictionary type. The key of the dictionary is the name attribute value of the label defined in the form form, and its value is the object of the uploaded file

Print the object of the uploaded file

def index(request):
    if request.method=="POST":

        print("files:",request.FILES.get("up_file"))
        print(type(request.FILES.get("up_file")))

    return render(request,"index.html",locals())

Print results

files: 1.png
<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>

The result shows that the type of file obtained is an upload file in memory

Get the name of the uploaded file in memory

def index(request):
    if request.method=="POST":

        print(type(request.FILES.get("up_file")))

        file_obj=request.FILES.get("up_file")

        print(file_obj.name)


    return render(request,"index.html",locals())

The results are as follows

<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
1.png

Now that you know the name of the file in memory, you can write the file to the server

def index(request):
    if request.method=="POST":
        file_obj=request.FILES.get("up_file")

        f1=open(file_obj.name,"wb")

        for i in file_obj.chunks():
            f1.write(i)

        f1.close()

    return render(request,"index.html",locals())

Select upload file again. After submitting, you can see the uploaded file in the background of the server

You can settings.py Set the path of the uploaded file in the file, or perform path splicing when opening the file handle to save the uploaded file in the specified directory

Posted by phpnewbieca on Thu, 11 Jun 2020 22:50:09 -0700