Django form by form and ajax upload files

Django form by form and ajax upload files

By default, form is not a form to transfer files. Even if we write a type in the type of input file as HTML tags. This is because the default HTML form transmission method application/x-www-form-urlencoded. However, this method can not transfer files. When using this method to transfer files, we can only see the file name in the back end, but not the entire file.

Views The view function when trying to print the acquired data file and POST, the following results:

<MultiValueDict: {}>
<QueryDict: {'csrfmiddlewaretoken': ['jEKPQOvvCeD4q96ET9zVU5xBTdlgmbgPQb7c5EhvNsrYdT8L4KBw8IuBTmlFOUwj'], 'avata': ['1571311850334.png']}>

At this time, we will form will form tag in the HTML code plus enctype="multipart/form-data"properties can upload files, modify the format of the message content-type header in the request carries during its essence:

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    用户名:<input type="text" name="username">
    头像: <input type="file" name="file_obj">
    <input type="submit">
</form>

writing view function views:

def upload(request):
    if request.method == 'GET':
        return render(request,'upload.html')
    else:
        print(request.POST)
        print(request.FILES)
        file_obj = request.FILES.get('file_obj')    # FILES 是一个类似于字典的对象,file_obj(也就是HTML文件input标签中的name属性值)对应的值才是文件对象
        print(file_obj.name)
        with open(file_obj.name,'wb') as f:
            # for i in file_obj:
            #     f.write(i)
            for i in file_obj.chunks():  # 65536字节
                f.write(i)
                return HttpResponse('ok')

When set enctype attribute of the form tag, the file will be successfully passed to the view function:

<MultiValueDict: {'avata': [<InMemoryUploadedFile: 1571311850334.png (image/png)>]}>
<QueryDict: {'csrfmiddlewaretoken': ['QTtPqw8y7nldamyW4uZzY6m5yzHglvGMnqQcFmUyiB97X6A3f51acJj5yIHFNeWg']}>

Get file_objis a file object, like a file handle. We can loop through direct file handles for the file line by line written to the local. Each line of the file if it is longer, such as media files like pictures, perhaps only one line, if we use the written line by line, it will take up a lot of memory resources. So more is recommended to use a for loop file_obj.chunks(), so that each cycle only 65,536 bytes of content, in order to ease the pressure on memory.

ajax upload files

ajax mainly js code, not to change the HTML, just add some real when id attribute to make it easier to find the target label:

{% csrf_token %}
用户名:<input type="text" name="username">
头像: <input type="file" name="file_obj">
<input type="submit" id="btn">

When using ajax upload files, you need to modify some js configuration. First, the file data can not be an ordinary custom objects saved, but need to use the new FormDatastatement to create a form data objects. Use command to append a key-value pair is inserted into the subject. You also need to value and processData contentType is set to false. This is done using ajax upload files with fixed, ajax not prompt for data processing operations:

$('#btn').click(function () {
    var formdata = new FormData();
    var uname = $('[name="username"]').val();
    // var file_obj = $('[name="file_obj"]').val(); //"C:\fakepath\0.jpg" 拿到的文件的本地路径
    var f_obj = $('[name="file_obj"]')[0].files[0] ; // 这是文件对象,注意是files而不是file

    formdata.append('username',uname);    // 将数据添加到formdata对象中
    formdata.append('file_obj',f_obj);
    formdata.append('csrfmiddlewaretoken',$('[name="csrfmiddlewaretoken"]').val());
    $.ajax({
        url:'/upload/',
        type:'post',
        // 上传文件时的固定搭配 formdata
        processData:false,
        contentType:false,
        data:formdata,
        // data:{uname:uname,file_obj:f_obj,'csrfmiddlewaretoken':$('[name="csrfmiddlewaretoken"]').val()},
        success:function (res) {
        console.log(res)
        }

    })
})

As view function, if the parameter does not change, you can completely not require modification.

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/12521586.html