微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ajax文件上传

文件上传

-普通上传
-自定义上传按钮
-基于Form做上传
-Ajax上传文件

views.py

from django.http import HttpResponse
from django.shortcuts import render
import json


# Create your views here.
def index(request):
    return render(request , 'index.html')


def ajax1(request):
    import time
    # time.sleep(5)

    print(request.GET)
    print(request.POST)
    # print(request.body)

    ret = {'status': True , 'message': '...'}
    import json
    return HttpResponse(json.dumps(ret))


def upload(request):
    return render(request , 'upload.html')


def upload_img(request):
    import os
    import uuid
    nid = str(uuid.uuid4())
    ret = {'status': True , 'data': None , 'message': 'None'}
    obj = request.FILES.get('k3')

    file_path = '/static/' + nid + obj.name

    BASE_DIR = os.path.join('static' , nid + obj.name)

    print(BASE_DIR)
    print(file_path)

    f = open(BASE_DIR , 'wb')
    for line in obj.chunks():
        f.write(line)
    f.close()
    ret['data'] = file_path
    return HttpResponse(json.dumps(ret))


def jsonp(request):
    return render(request , 'jsonp.html')


def ajax3(request):
    return HttpResponse('ok2')

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <style>
        .btn {
            display: inline-block;
            padding: 5px 10px;
            background: coral;
            color: white;
        }
    </style>
</head>

<body>
<h1>Ajax全套</h1>
<h3>1.Ajax发送GET请求</h3>
<div>
    <a href="#" class="btn" onclick="AjaxSubmit1();">click_here</a>
    <a href="#" class="btn" onclick="AjaxSubmit2();">click_here</a>
</div>
<h3>2.Ajax发送POST请求</h3>
<div>
    <a href="#" class="btn" onclick="AjaxSubmit3();">click_here</a>
    <a href="#" class="btn" onclick="AjaxSubmit4();">click_here</a>
</div>
<h3>3.伪Ajax</h3>
<div>
    <h6>基于Iframe+Form表单</h6>
    <iframe id="iframe" name="ifra"></iframe>
    <form action="/ajax1.html/" id="fm" method="post" target="ifra">
        <input type="text" name="root" value="111"/>
        <a onclick="AjaxSubmit5();">提交</a>
    </form>
</div>

<h3>4.文件上传</h3>
<input type="file" id="img"/>
<a href="#" class="btn" onclick="AjaxSubmit6();">上传</a>
<a href="#" class="btn" onclick="AjaxSubmit7();">上传</a>


<iframe style="display:none;" id="iframe1" name="ifra1"></iframe>
<form action="/ajax1.html/" id="fm" method="post" enctype="multipart/form-data" target="ifra1">
    <input type="text" name="k1"/>
    <input type="text" name="k2"/>
    <input type="text" name="k3"/>
    <input name="root" id="img"/>
    <a onclick="AjaxSubmit8();">提交</a>
</form>

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


    function AjaxSubmit1() {
        $.ajax({
            url: '/ajax1.html',
            type: 'GET',
            data: {'p': 123},
            success: function (arg) {

            }
        })
    }

    function AjaxSubmit2() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //接收完毕服务器返回的数据
                console.log(xhr.responseText)
            }
        };
        xhr.open('GET', '/ajax1.html?P=123');
        xhr.send(null);
    }

    function AjaxSubmit3() {
        $.ajax({
            url: '/ajax1.html/',
            type: 'POST',
            data: {'p': 123},
            success: function (arg) {

            }
        })
    }

    function AjaxSubmit4() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //接收完毕服务器返回的数据
                console.log(xhr.responseText)
            }
        };
        xhr.open('POST', '/ajax1.html/');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
        xhr.send("p=456");
    }

    function AjaxSubmit5() {
        document.getElementById('iframe').onload = reloadIframe;
        document.getElementById('fm').submit();
    }

    function reloadIframe() {
        
        console.log(this.contentwindow.document.body.innerHTML);
        $(ths).contents().find('body').html();

        var content = this.contentwindow.document.body.innerHTML;
        var obj = JSON.parse(content);
        if (obj.status) {
            alert(obj.message)
        }
    }

    function AjaxSubmit6() {
        //var a=document.getElementById('img').files[0];
        var data = new FormData();
        data.append('k1', 'v1');
        data.append('k2', document.getElementById('img').files[0]);
        $.ajax({
            url: '/ajax1.html/',
            type: 'POST',
            data: data,
            success: function (arg) {
                console.log(arg)
            },
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
        })
    }

    function AjaxSubmit7() {
        var data = new FormData();
        data.append('k1', 'v1');

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //接收完毕服务器返回的数据
                console.log(xhr.responseText)
            }
        };
        xhr.open('GET', '/ajax1.html?P=123');
        xhr.send(data);
    }

    function AjaxSubmit8() {
        document.getElementById('iframe1').onload = reloadIframe1;
        document.getElementById('fm1').submit();
    }

    function reloadIframe1() {
        var content = this.contentwindow.document.body.innerHTML;
        var obj = JSON.parse(content);
        console.log(obj)
    }

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

图片上传预览

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <style>
        .btn {
            display: inline-block;
            padding: 5px 10px;
            background: coral;
            color: white;
        }
    </style>
</head>

<body>


<iframe style="display:none;" id="iframe1" name="ifra1"></iframe>
<form action="/upload_img.html/" id="fm1" method="post" enctype="multipart/form-data" target="ifra1">
    <input type="file" name="k3" onchange="uploadFile();"/>
    <a onclick="AjaxSubmit8();">提交</a>
</form>

<h3>预览</h3>
<div id="preview">
{#    <img src="/static/15239.jpg" alt="">#}
</div>

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


    function uploadFile() {
        document.getElementById('iframe1').onload = reloadIframe1;
        document.getElementById('fm1').submit();
    }

    function reloadIframe1() {
        var content = this.contentwindow.document.body.innerHTML;
        var obj = JSON.parse(content);
        console.log(obj.data);
        var tag=document.createElement('img');
        tag.src=obj.data;
        console.log(tag);
        $("#preview").empty().append(tag);
    }

</script>
</body>
</html>
def upload_img(request):
    import os
    import uuid
    nid = str(uuid.uuid4())
    ret = {'status': True , 'data': None , 'message': 'None'}
    obj = request.FILES.get('k3')
    file_path = '/static/' + nid + obj.name
    BASE_DIR = os.path.join('static' , nid + obj.name)
    print(BASE_DIR)
    print(file_path)
    f = open(BASE_DIR , 'wb')
    for line in obj.chunks():
        f.write(line)
    f.close()
    ret['data'] = file_path
    return HttpResponse(json.dumps(ret))

JSONP 跨域

浏览器同源策略:XMLHttpReauest
     JSONP巧妙的机制
    
     JSONP:利用创建script块,在其中执行src属性为:远程url
             函数(返回值)
            
             function 函数(arg){
                 ...
             }
             只能发GET

jsonp.html

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<div id="content"></div>
<input type="button" value="发送1" onclick="submitJsonp1();"/>
<input type="button" value="发送2" onclick="submitJsonp2();"/>
<input type="button" value="发送3" onclick="submitJsonp3();"/>
<input type="button" value="发送4" onclick="submitJsonp4();"/>
<script src="/static/js/jquery-3.1.1.js"></script>
<script>
    function submitJsonp1() {
        $.ajax({
            url: 'http://127.0.0.1:9000/kuayu/',
            type: 'GET',
            data: {nid: 2},
            success: function (arg) {
                $('#content').html(arg);
            }
        })
    }

    function submitJsonp2() {
        var tag = document.createElement('script');
        tag.src = 'http://127.0.0.1:9000/kuayu/';
        document.head.appendChild(tag);
        document.head.removeChild(tag);
    }

    function submitJsonp3() {
        var tag = document.createElement('script');
        tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403%27';
        document.head.appendChild(tag);
        document.head.removeChild(tag);
    }

    function list1(arg) {
        console.log(arg)
    }

    function submitJsonp4() {
        $.ajax({
            url: 'http://127.0.0.1:9000/kuayu/',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'list',
        })
    }

    function list(arg) {
        console.log(arg)
    }

</script>
</body>
</html>
def kuayu(request):
    name = request.GET.get('callback')
    return HttpResponse('%s("ok3");' % (name ,))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐