发送文件的三种方式

window['XMLHttpRequest']

window.XMLHttpRequest

XMLHttpRequest

。。。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type=button value="ajax1" onclick="ajax1();"/>
<input type="text"/>
<script>
    {#        此函数为固定用法,处理各个服务器之间的兼容性问题#}
    function getXHR() {
var xhr = null;
        if (XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xhr;

    }
    function ajax1() {
        var xhr = getXHR();
        xhr.open("POST", '/ajaxjson/', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //接受完毕
                {#                    console.log(xhr.responseText);#}
                var obj = JSON.parse(xhr.responseText);
                console.log(obj)
            }
        };
        xhr.setRequestHeader('k1', 'v1');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
        xhr.send("name=root;pwd=123");

    }
</script>
</body>
</html>

三种方式提交文件

后台接受数据通用函数

# upload函数,从这个页面发送请求
def upload(request):
    return render(request, 'upload.html')

#这个函数用来接收发过来的文件信息
def upload_files(request):
    #接收文件及数据
    username = request.POST.get('username')
    fasong = request.FILES.get('fasong')
    print(username)
    print(fasong)
    
    # 定义文件接收后要存储的路径
    import os
    files_path = os.path.join('templates/', fasong.name)
    print(files_path)
    with open(files_path, 'wb') as f:
        for item in fasong.chunks():
            f.write(item)

    # 存完后返回信息到ifroma框中
    ret = {'status': True, 'data': request.POST.get('username')}
    import json
    return HttpResponse(json.dumps(ret))

方式一的HTML实例

原生的ajax方式的提交

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <form>
 9     <input type="file" id="fasong">
10     <input type="button" value="提交form" onclick="xhrsbmit();"/>
11 </form>
12 
13 <script src="/static/jquery-1.12.4.js"></script>
14 
15 <script>
16     function xhrsbmit() {
17         var file_obj = document.getElementById('fasong').files[0];
18         {# 上传得文件对象 #}
19         var fd = new FormData();
20         fd.append('username', 'root');
21         fd.append('fasong', file_obj);
22         var xhr = new XMLHttpRequest();
23         xhr.open("POST", '/upload_files/', true);
24         xhr.onreadystatechange = function () {
25             if (xhr.readyState == 4) {
26                 //接受完毕
27                 {#                    console.log(xhr.responseText);#}
28                 var obj = JSON.parse(xhr.responseText);
29                 console.log(obj)
30             }
31         };
32         xhr.send(fd);
33     }
34 </script>
35 </body>
36 </html>

方式jquery方式提交

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <form>
 9     <input type="file" id="fasong">
10     <input type="button" value="提交jquery" onclick="jquerysbmit();"/>
11 </form>
12 
13 <script src="/static/jquery-1.12.4.js"></script>
14 <script>
15     function jquerysbmit() {
16         var file_obj = document.getElementById('fasong').files[0];
17         {# 上传得文件对象 #}
18         var fd = new FormData();
19         fd.append('username', 'root');
20         fd.append('fasong', file_obj);
21         $.ajax({
22             url: "/upload_files/",
23             type: "POST",
24             data: fd,
25             processData: false, {# 不处理数据 #}
26             contentType: false, {# 不处理数据类型 #}
27             success: function (arg, a1, a2) {
28                 console.log(arg);
29                 console.log(a1);
30                 console.log(a2);
31 
32             }
33         });
34     }
35 </script>
36 </body>
37 </html>

方式三,原生的Ajax和jQuery都实现了文件的上传,但是这两者都依赖于FormData (低版本的又不支持)

需要用iframe的方式提交(兼容所有的浏览器,最主要是兼容IE)上传文件的第3种方式。

不依赖于FormData

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <div>
 9     <form method="POST" action="/upload_files/" enctype="multipart/form-data" target="ifm1">
10         <iframe id="ifm1" name="ifm1"></iframe>
11         {#        <input type="text" name="username" placeholder="用户名">#}
12         <input type="file" name="fasong">
13         <input type="submit" onclick="fr_fasong();" value="Fram提交">
14     </form>
15 </div>
16 <script src="/static/jquery-1.12.4.js"></script>
17 <script>
18     {# 定义submit_iframe提交时的鼠标事件,在鼠标点击之后为ifrom添加一个load事件 #}
19     function fr_fasong() {
20         $('#ifm1').load(function () {
21             var text = $('#ifm1').contents().find('body').text();
22             var obj = JSON.parse(text);
23             console.log(obj);
24         });
25     }
26 </script>
27 </body>
28 </html>

以上三种方法都可以提交文件

原文地址:https://www.cnblogs.com/cerofang/p/8449524.html