models渲染字典&form表單上傳文件&ajax上傳文件

{#    {% for u in teacher_d.keys %}#}
{#    {% for u in teacher_d.values %}#}
    {% for k,u in teacher_d.items %}
        <input type="text" value="{{ k }}">
        <input type="text" value="{{ u }}">
    {% endfor %}

  

user_dict = {
            "1":"sb1",
            "2":"sb2"
        }
        return render(request,"teacher.html",{"teacher_list":new_teacher_list,"teacher_d":user_dict})

  

基於form上傳文件,咱們通常會把文件上傳到指定的路徑,而後在數據庫中存儲文件和對應的路徑的地址html

 

前端上傳文件的代碼前端

<body>
    <form method="post" action="/user_manager_app1/upload/" enctype="multipart/form-data">
{#        enctype="multipart/form-data"若是在form標籤中加上這一個屬性,則上傳的問題就不在request.POST中了,而在request.FILES中#}
        <input type="text" name="name">
        <input type="file" name="file">
        <input type="submit" value="sum提交">
    </form>
    <h1>文件展現</h1>
    <table border="1">
        <caption>數據庫中的文件</caption>
        <thead>
            <tr>
                <th>文件名稱</th>
                <th>文件路徑</th>
                <th>上傳時間</th>
                <th>文件大小</th>
                <th>文件操做</th>
            </tr>
        </thead>
        <tbody>
            {% for file in file_data %}
                <tr>
                    <td>{{ file.file_name }}</td>
                    <td>{{ file.file_path }}</td>
                    <td>{{ file.file_time }}</td>
                    <td>{{ file.file_size }}</td>
                    <td>查看|刪除</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    
   
</body>

  

後端處理的代碼python

def upload(reqeust):
    if reqeust.method.lower() == "get":
        file_all = models.file.objects.all()
        return render(reqeust,"upload.html",{"file_data":file_all})

    else:
        name = reqeust.POST.get("name")
        file = reqeust.POST.get("file")
        file_new = reqeust.FILES.get("file")

        print("上傳的文件的名稱",file_new.name,"文件的大小",file_new.size)
        file_path = os.path.join("static","upload",file_new.name)
        with open(file_path,"wb") as f:
            for chunk in file_new.chunks():
                f.write(chunk)
        models.file.objects.create(
            file_path = file_path,
            file_name =  file_new.name,
            file_time = time.ctime(),
            file_size = file_new.size
        )
        return redirect("/user_manager_app1/upload/")

  

 -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------jquery

經過ajax上傳文件ajax

前端代碼--html數據庫

<h1>formData方式上傳</h1>
    <div id="imgs">
    </div>
    <input type="file" id="upload_file">
    <input type="button" value="點擊上傳" id="upload_button">
    <span id="errors"></span>

  

前端代碼--jqueryjson

<script src="/static/jq/jquery-3.3.1.js"></script>

    <script>
        $(function () {
            upload_file()
        })
        
        function upload_file() {

            $("#upload_button").bind("click",function () {
{#                $("#errors").html()#}
                var dict = new FormData()
                dict.append("file",document.getElementById("upload_file").files[0])

                $.ajax(
                    {
                        url:"/app1/upload_ajax/",
                        type:"POST",
                        data:dict,
                        success:function (data) {
                            data = JSON.parse(data)
                            if(data["state"] == "true"){
                                var img = document.createElement("img");
                                img.src = "/" + data["file_path"];
                
                                var father_ele = document.getElementById("imgs");
                                father_ele.appendChild(img);
{#                                window.location.reload()#}
                            }else {
                                $("#errors").html(data["error"])
                            }
                        },
                        processData:false,
                        contentType:false
                    }
                )
            })

        }
        
    </script>

  

這裏有三個點須要注意後端

a、這裏須要個formdata的對象,把咱們上傳的文件經過append的方法添加到這個formdata對象中,而後經過ajax把這個formdata對象發送給後端就能夠了app

先找到上傳文件的input的標籤,這裏咱們經過id去定位到input的標籤post

 

 

 

 b、經過ajax直接把這個數據發送給後端,這裏要注意,咱們的data就是上面咱們建立的formdata對象中

 

 

 c、若是ajax要向後端發送數據,則必需要還有設置兩個類型

 

 

最後咱們看下後端的代碼,後端也是要在request.Files中獲取文件對象,而後寫到本地就能夠了

def upload_ajax(request):
    import os
    import json
    method = request.method.lower()
    if method == "get":
        return render(request,"upload.html")
    else:
        res = {"state":"true","file_path":None,"error":""}
        file = request.FILES.get("file")
        print(file)
        file_path = os.path.join("static","file",file.name)

        try:
            with open(file_path,"wb") as f:
                for chunk in file.chunks():
                    f.write(chunk)

        except Exception as e:
            print(e)
            res["state"] = "false"
            res["error"] = "上傳失敗"
            return HttpResponse(json.dumps(res))
        else:
            res["file_path"] = file_path

            return HttpResponse(json.dumps(res))
相關文章
相關標籤/搜索