AJAX and from upload file example [django project]

Keywords: Programming JQuery Django Python

Project brief

This Django project is a test case project for learning tests.

Three ways to upload Django files (form, jQuery+jQuery.ajax, native JS + native ajax) are used as the upload function examples

file Interpretation of documents
form_upload.html form upload file static page
jquery_ajax_upload.html jQuery+jQuery.ajax upload file static page
js_ajax_upload.html Native JS + native ajax upload file static page
Fupload.py form upload file method
JAupload.py Native JS + native ajax upload file method
JQupload.py Method of uploading files in jQuery+jQuery.ajax

Project framework

Mydjango
    APP
        file
        migrations
            __init__.py
        static
            jquery-3.3.1.min.js
        templates
            form_upload.html
            jquery_ajax_upload.html
            js_ajax_upload.html
        views
            Fupload.py
            JAupload.py
            JQupload.py
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
    Mydjango
        setting.py
        urls.py
        wsgi.py

Project example

Create project

django-admin startproject Mydjango
cd Mydjango
python manage.py startapp APP

form_upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>form upload</title>
</head>
<body>
<h1>form Method upload and submit</h1>
<!--   Include necessary parameters for uploading files enctyoe -->
     <form action="f_upload.html" method="POST" enctype="multipart/form-data">
         {% csrf_token %}
         <!-- Upload files to name parameter -->
         <input type="file" name="uploadfile">
         <input type="submit">
     </form>
</body>
</html>

jquery_ajax_upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax upload</title>
    <script src="../static/jquery-3.3.1.min.js"></script>
</head>
<body>

<h1>jQuery+jQuery Manner ajax Upload submit</h1>
<!--   Include necessary parameters for uploading files enctyoe -->
{% csrf_token %}
         <input id="Upfile" type="file"  multiple="multiple" >
         <a id="FileSub">Submission</a>

<script>
    $("#FileSub").click(function() {

        var f_obj = $("#Upfile").get(0).files[0]; / / get the upload file information
        console.log("File object:",f_obj);
        console.log("The file name is:",f_obj.name);
        console.log("The file size is:",f_obj.size);

        var data = new FormData();                                      //Create formdata objects to facilitate file transfer to the back end
        data.append("file",f_obj)                                        //To add (encapsulate) a file object to a formdata object

        $.ajax({
            url:'jq_upload.html',
            type:'POST',
            data:data,
            cache: false,                                               //Upload files without caching
            processData:false,                                          //Do not serialize data
            contentType:false,                                          //No special connection type defined
            success:function (arg) {
                alert("The file has been uploaded successfully. Click OK to refresh the page");
                location.reload();
                                    }
            })
        });
</script>
</body>
</html>

js_ajax_upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax upload</title>
</head>
<body>

<h1>Native js+Native ajax Method upload and submit</h1>
<!--   Include necessary parameters for uploading files enctyoe -->
{% csrf_token %}
         <input id="Upfile" type="file"  multiple="multiple" >
         <a onclick="Js_Ajax();">Submission</a>

<script>
    function Js_Ajax() {
        var xhr = new XMLHttpRequest();                                                         //Create an empty object to transport the back end
        xhr.onreadystatechange = function () {                                                  //Specify callback function
            if (xhr.readyState == 4) {                                                           //Callback function state judgment
                console.log("Return information:", xhr.responseText);
                alert("The file has been uploaded successfully. Click OK to refresh the page");
                location.reload();
            }
        };
        xhr.open('POST', 'ja_upload.html');                                                       //Set up POST mode request
        xhr.setRequestHeader('Conten-Type', 'application/x-www-foorm-urlencoded;charset-UTF-8');  //POST data request header

        var f_obj = document.getElementById("Upfile").files[0];                                   //Get uploaded file object
        console.log("File object:", f_obj);
        console.log("The file name is:", f_obj.name);
        console.log("The file size is:", f_obj.size);

        var data = new FormData();                                                                //Create formdata objects to facilitate file transfer to the back end
        data.append("file", f_obj);                                                                //To add (encapsulate) a file object to a formdata object

        xhr.send(data);                                                                            //Data sent by established POST request
    };
</script>
</body>
</html>

Fupload.py

# -*- coding:utf8 -*-
from django.shortcuts import render,HttpResponse


def F_Upload(request):                 # Submit upload file in form
    if request.method == "GET":
        return render(request, 'form_upload.html', )
    else:
        F = request.FILES
        print("form The uploaded file is:",F)                   #You can see a dictionary that protects file names and file objects
        f_obj = F.get('uploadfile')                     #Uploaded file object

        N = f_obj.name                                  #Uploaded file name
        S = f_obj.size                                  #Uploaded file size

        print("The file name is:",N)
        print("The file size is:",S)

        W_File(f_obj)                                   #How to upload files
        return HttpResponse('File upload succeeded!')
def W_File(file_obj):                                   #Upload file is written to the server, and the parameter is the uploaded file object
    f = open('APP/file/' + file_obj.name + "", 'wb')    # The server creates and uploads a file with the same name
    for line in file_obj.chunks():                      # Take and upload data in blocks
        f.write(line)                                   # Write the obtained data block to the server circularly
    f.close()

JAupload.py

# -*- coding:utf8 -*-
from django.shortcuts import render,HttpResponse

def JA_Upload(request):
    if request.method == "GET":
        return render(request,'js_ajax_upload.html',)
    else:
        file_obj = request.FILES.get('file')                # Get the file data from
        print("The name of the uploaded file is:", file_obj.name)
        print("The size of the uploaded file is:", file_obj.size)

        f = open('APP/file/' + file_obj.name + "", 'wb')    # The server creates and uploads a file with the same name
        for line in file_obj.chunks():                      # Take and upload data in blocks
            f.write(line)                                   # Write the obtained data block to the server circularly
        f.close()
        return HttpResponse('File upload succeeded!')

JQupload.py

# -*- coding:utf8 -*-
from django.shortcuts import render,HttpResponse

def JQ_Upload(request):
    if request.method == "GET":
        return render(request,'jquery_ajax_upload.html',)
    else:
        file_obj = request.FILES.get('file')                # Get the file data from
        print("The name of the uploaded file is:", file_obj.name)
        print("The size of the uploaded file is:", file_obj.size)

        f = open('APP/file/' + file_obj.name + "", 'wb')    # The server creates and uploads a file with the same name
        for line in file_obj.chunks():                      # Take and upload data in blocks
            f.write(line)                                   # Write the obtained data block to the server circularly
        f.close()
        return HttpResponse(file_obj.name)

urls.py

from django.contrib import admin
from django.urls import path,re_path
from APP.views import Fupload,JAupload,JQupload

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^f_upload.html$',Fupload.F_Upload),
    re_path('^ja_upload.html$',JAupload.JA_Upload),
    re_path('^jq_upload.html$',JQupload.JQ_Upload),
]

setting.py

Installed? APP added

'APP',

MIDDLEWARE

Comment out the csrf part
#'django.middleware.csrf.CsrfViewMiddleware',

TEMPLATES configuration template path

'DIRS': [os.path.join(BASE_DIR, 'APP/templates')],

Run test access test

python manage.py runserver

Access address

http://127.0.0.1:8000/f_upload.html
http://127.0.0.1:8000/jq_upload.html
http://127.0.0.1:8000/ja_upload.html

Posted by matt_wood87 on Tue, 10 Dec 2019 17:10:56 -0800