1. 程式人生 > >Django-Ajax進階

Django-Ajax進階

load .post enc src sub ryu user memory word

Ajax上傳文件

1、form表單上傳文件

文件和其他的數據類型不一樣,是一個二進制的形式

Form上傳文件的時候切記要加上:enctype="multipart/form-data"

formupload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content
="width=device-width"> <title>Title</title> </head> <body> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script> <script src="https://cdn.bootcss.com/jquerycookie/1.4.1/jquery.cookie.js"></script> <form action="/formupload/" method="post" enctype
="multipart/form-data"> {% csrf_token %} <p>姓名:<input type="text" name="username"></p> <p>密碼:<input type="password" name="password"></p> <p>頭像:<input type="file" name="file"></p> <p><input type="submit" value="提交"></
p> </form> </body> </html>

view.py

def formupload(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        # file = request.FILES   #拿到的是一個句柄
        file_obj = request.FILES.get("file")
        print(file_obj,file_obj.name)
        print(type(file_obj),type(file_obj.name))   #<class ‘django.core.files.uploadedfile.InMemoryUploadedFile‘>   <class ‘str‘>
        with open(file_obj.name,"wb") as f:
            for i in file_obj:
                f.write(i)
        return HttpResponse("上傳成功...")
    return render(request,"formupload.html")

2Ajax上傳文件(利用FormData

FormData是什麽呢?

XMLHttpRequest Level 2添加了一個新的接口FormData.利用FormData對象,我們可以通過JavaScript用一些鍵值對來模擬一系列表單控件,我們還可以使用XMLHttpRequest的send()方法來異步的提交這個"表單".比起普通的ajax,使用FormData的最大優點就是我們可以異步上傳一個二進制文件.

所有主流瀏覽器的較新版本都已經支持這個對象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+

要是使用FormData一定要加上:

一定要加上:

contentType:false
  processDate:false #不做預處理

ajaxupload.html

<h3>Ajax上傳文件</h3>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script src="https://cdn.bootcss.com/jquerycookie/1.4.1/jquery.cookie.js"></script>
<p><input type="text" name="username" id="username" placeholder="username"></p>
<p><input type="file" name="upload_file_ajax" id="upload_file_ajax"></p>

<button id="upload_button">提交</button>
{#註意button標簽不要用在form表單中使用#}

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

        var username=$("#username").val();
        var upload_file=$("#upload_file_ajax")[0].files[0];

        var formData=new FormData();
        formData.append("username",username);
        formData.append("upload_file_ajax",upload_file);


        $.ajax({
            url:"/upload_file/",
            type:"POST",
            data:formData,
            contentType:false,
            processData:false,

            success:function(){
                alert("上傳成功!")
            }
        });
    })
</script>

views.py

def index(request):
    return render(request,"index.html")

def upload_file(request):
    print("FILES:",request.FILES)
    print("POST:",request.POST)
return HttpResponse("上傳成功!")

3、偽造Ajax上傳文件

iframe標簽

<iframe> 標簽規定一個內聯框架。

一個內聯框架被用來在當前 HTML 文檔中嵌入另一個文檔。

示例:

<iframe src="http://www.baidu.com" width="1000px" height="600px"></iframe>

iframe+form

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script src="https://cdn.bootcss.com/jquerycookie/1.4.1/jquery.cookie.js"></script>
<h3>偽造Ajax上傳文件</h3>


<form action="/upload_file/" method="post" id="form2" target="ifr" enctype="multipart/form-data"> <p><iframe name="ifr" id="ifr"></iframe></p> <p><input type="file" name="upload_file"></p> <p><input type="text" name="user"></p> <input type="button" value="提交" id="submitBtn"> </form> <script> $("#submitBtn").click(function(){ $("#ifr").load(iframeLoaded); $("#form2").submit(); }); function iframeLoaded(){ alert(123) } </script>

views

def index(request):
 
    return render(request,"index.html")
 
def upload_file(request):
    print("FILES:",request.FILES)
    print("POST:",request.POST)
return HttpResponse("上傳成功!")

Django-Ajax進階