【django】ajax,上传文件,图片预览

1.ajax

概述:

AJAX = 异步 JavaScript 和 XML。

AJAX 是一种用于创建快速动态网页的技术。

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新,而传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。

1.1  原生Ajax

原生Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。

XmlHttpRequest对象的主要方法:

a. void open(String method,String url,Boolen async)
   用于创建请求
    
   参数:
       method: 请求方式(字符串类型),如:POST、GET、DELETE...
       url:    要请求的地址(字符串类型)
       async:  是否异步(布尔类型)
 
b. void send(String body)
    用于发送请求
 
    参数:
        body: 要发送的数据(字符串类型)
 
c. void setRequestHeader(String header,String value)
    用于设置请求头
 
    参数:
        header: 请求头的key(字符串类型)
        vlaue:  请求头的value(字符串类型)
 
d. String getAllResponseHeaders()
    获取所有响应头
 
    返回值:
        响应头数据(字符串类型)
 
e. String getResponseHeader(String header)
    获取响应头中指定header的值
 
    参数:
        header: 响应头的key(字符串类型)
 
    返回值:
        响应头中指定的header对应的值
 
f. void abort()
 
    终止请求

XmlHttpRequest对象的主要属性:

a. Number readyState
   状态值(整数)
 
   详细:
      0-未初始化,尚未调用open()方法;
      1-启动,调用了open()方法,未调用send()方法;
      2-发送,已经调用了send()方法,未接收到响应;
      3-接收,已经接收到部分响应数据;
      4-完成,已经接收到全部响应数据;
 
b. Function onreadystatechange
   当readyState的值改变时自动触发执行其对应的函数(回调函数)
 
c. String responseText
   服务器返回的数据(字符串类型)
 
d. XmlDocument responseXML
   服务器返回的数据(Xml对象)
 
e. Number states
   状态码(整数),如:200、404...
 
f. String statesText
   状态文本(字符串),如:OK、NotFound...

基于原生AJAX案例:

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^ajax/', views.ajax),
    url(r'^json/', views.json),
]
project/urls.py
def ajax(request):
    return render(request,'ajax.html')

def json(requset):
    ret = {'status':True,'data':None)}
    import json
    return HttpResponse(json.dumps(ret))
app01/views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text"/>
    <input type="button" value="Ajax1" onclick="Ajax1();"/>

    <script src="/static/jquery-1.12.4.js/"></script>
    <script>
        //跨浏览器支持
        function getXHR(){
            var xhr = null;
            if(XMLHttpRequest){
                xhr = new XMLHttpRequest();
            }else{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhr;
        }

        function Ajax1() {
            var xhr = new getXHR();
            xhr.open('POST','/json/',true);
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    //接收完毕,执行以下操作
                    //console.log(xhr.responseText);
                    var obj = JSON.parse(xhr.responseText);
                    console.log(obj);
                }
            };
            // 设置请求头,后端输入print(requset.POST),可获取send数据
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
            //只能是字符串格式
            xhr.send("name=root;pwd=123")
        }

    </script>
</body>
</html>
templates/ajax.html

 1.2  ajax jquery

jQuery其实就是一个JavaScript的类库(JS框架),其将复杂的功能做了上层封装,使得开发者可以在其基础上写更少的代码实现更多的功能。

  • jQuery 不是生产者,而是大自然搬运工。
  • jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject 

jQuery Ajax 方法列表:

jQuery.get(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数。
                 success: 载入成功时回调函数。
                dataType: 返回内容格式,xml, json,  script, text, html


            jQuery.post(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数
                 success: 载入成功时回调函数
                dataType: 返回内容格式,xml, json,  script, text, html


            jQuery.getJSON(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数。
                 success: 载入成功时回调函数。


            jQuery.getScript(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数。
                 success: 载入成功时回调函数。


            jQuery.ajax(...)

                部分参数:

                        url:请求地址
                       type:请求方式,GET、POST(1.9.0之后用method)
                    headers:请求头
                       data:要发送的数据
                contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
                      async:是否异步
                    timeout:设置请求超时时间(毫秒)

                 beforeSend:发送请求前执行的函数(全局)
                   complete:完成之后执行的回调函数(全局)
                    success:成功之后执行的回调函数(全局)
                      error:失败之后执行的回调函数(全局)
                

                    accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
                   dataType:将服务器端返回的数据转换成指定类型
                                   "xml": 将服务器端返回的内容转换成xml格式
                                  "text": 将服务器端返回的内容转换成普通文本格式
                                  "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
                                "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
                                  "json": 将服务器端返回的内容转换成相应的JavaScript对象
                                 "jsonp": JSONP 格式
                                          使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

                                  如果不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string

                 converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数
                         $.ajax({
                              accepts: {
                                mycustomtype: 'application/x-some-custom-type'
                              },
                              
                              // Expect a `mycustomtype` back from server
                              dataType: 'mycustomtype'

                              // Instructions for how to deserialize a `mycustomtype`
                              converters: {
                                'text mycustomtype': function(result) {
                                  // Do Stuff
                                  return newresult;
                                }
                              },
                            }); 

基于jQueryAjax-demo

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

    <p>
        <input type="button" onclick="XmlSendRequest();" value='Ajax请求' />
    </p>


    <script type="text/javascript" src="jquery-1.12.4.js"></script>
    <script>

        function JqSendRequest(){
            $.ajax({
                url: "http://c2.com:8000/test/",   //  数据提交地址
                type: 'GET',               //提交类型
                dataType: 'text',         //提交的内容 字典格式
                success: function(data, statusText, xmlHttpRequest){
                    console.log(data);   // data是服务器端返回的字符串
                    var obj = JSON.parse(data);     // 反序列化 把字符串data换成对象obj
                                                                // 序列化 JSON.stringify() 把obj转换为字符串
                    if(obj.status){
                        location.reload()   // 重新加载页面
                    }else {
                        $('#error_msg').text(obj.error)
                    }
                }
            })
        }


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

 # 建议:永远让服务器端返回一个字典
# return HttpResponse(json.dumps(字典))            

 1.3  “伪”AJAX

由于HTML标签的iframe标签具有局部加载内容的特性,所以可以使用其来伪造Ajax请求。

① Form表单提交到iframe中,页面不刷新

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="text"/>
    <input type="button" value="Ajax1" onclick="Ajax1();" />
 
    <form action="/ajax_json/" method="POST" target="ifm1"> <!-- target跟iframe进行关联 -->
        <iframe id="ifm1" name="ifm1" ></iframe>
        <input type="text" name="username" />
        <input type="text" name="email" />
        <input type="submit" value="Form提交"/>
    </form>
</body>
</html>②.Ajax提交到iframe中,页面不刷新

② Ajax提交到iframe中,页面不刷新

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="text"/>
    <input type="button" value="Ajax1" onclick="Ajax1();" />
 
    <input type='text' id="url" />
    <input type="button" value="发送Iframe请求" onclick="iframeRequest();" />
    <iframe id="ifm" src="http://www.baidu.com"></iframe>
 
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
 
        function iframeRequest(){
            var url = $('#url').val();
            $('#ifm').attr('src',url);
        }
    </script>
</body>
</html>③.Form表单提交到iframe中,并拿到iframe中的数据

③ Form表单提交到iframe中,并拿到iframe中的数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="text"/>
    <input type="button" value="Ajax1" onclick="Ajax1();" />
 
    <form action="/ajax_json/" method="POST" target="ifm1">
        <iframe id="ifm1" name="ifm1" ></iframe>
        <input type="text" name="username" />
        <input type="text" name="email" />
        <input type="submit" onclick="submitForm();" value="Form提交"/>
    </form>
 
    <script type="text/javascript" src="/static/jquery-1.12.4.js"></script>
    <script>
        function submitForm(){
            $('#ifm1').load(function(){
                var text = $('#ifm1').contents().find('body').text();
                var obj = JSON.parse(text);
                console.log(obj)
            })
        }
    </script>
</body>
</html>

2.上传文件

2.1  Form表单上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload.html" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="text" name="user"/>
        <input type="file" name="img"/>
        <input type="submit" value="提交">
    </form>
</body>
</html>
html
from django.shortcuts import render
from django.shortcuts import HttpResponse

# Create your views here.

def upload(request):
    if request.method == "GET":
        return  render(request,'upload.html')
    else:
        user = request.POST.get('user')
        img = request.FILES.get('img')
        #img是个对象(文件大小,文件名称,文件内容...)
        print(img.name)
        print(img.size)
        n = open(img.name,'wb')
        for i in img.chunks():
            n.write(i)
        n.close()
        return HttpResponse('...!')
python

伪装上传按钮样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload.html" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="text" name="user"/>
        <div style="position: relative">
            <a>上传图片</a>
            <input type="file" name="img" style="opacity: 0.2;position:absolute;top: 0;left: 0" />
        </div>
        <input type="submit" value="提交">
    </form>
</body>
</html>
html

2.2  AJAX上传

基于原生Aja(XmlHttpRequest)上传文件

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^upload/$', views.upload),
    url(r'^upload_file/$', views.upload_file),
]
project/urls.py
def upload(request):
    return render(request,'upload.html')

def upload_file(request):
    username = request.POST.get('username')
    send = request.FILES.get('send')
    print(username,send)
    with open(send.name,'wb') as f:
        for item in send.chunks():
            f.write(item)

    ret = {'status': True, 'data': request.POST.get('username')}
    import json
    return HttpResponse(json.dumps(ret))
app01/views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .upload{
            display: inline-block;padding: 5px 10px;
            background-color: dodgerblue;
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom:0px;
            z-index: 90;
        }
        .file{
             100px;height: 50px;opacity: 0;
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom:0px;
            z-index: 100;
        }
    </style>
</head>
<body>
    <div style="position: relative; 100px;height: 50px">
        <input class="file" type="file" id="send" name="afafaf"/>
        <a class="upload">上传</a>
    </div>
     <input type="button" value="提交xmlhttprequest" onclick="xhrSubmit();"/>

    <script>
        function xhrSubmit() {
            //$('#send')[0]
            var file_obj = document.getElementById('send').files[0];

            var fd = new FormData();
            fd.append('username','root');
            fd.append('send',file_obj);

            var xhr = new XMLHttpRequest();
            xhr.open('POST','/upload_file/',true);
            xhr.send(fd);
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    //接收完毕,执行以下操作
                    //console.log(xhr.responseText);
                    var obj = JSON.parse(xhr.responseText);
                    console.log(obj);
                }
            };
        }
    </script>
</body>
</html>
templates/upload.html

基于Ajax JQuery进行文件的上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .upload{
            display: inline-block;padding: 5px 10px;
            background-color: dodgerblue;
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom:0px;
            z-index: 90;
        }
        .file{
             100px;height: 50px;opacity: 0;
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom:0px;
            z-index: 100;
        }
    </style>
</head>
<body>
    <div style="position: relative; 100px;height: 50px">
        <input class="file" type="file" id="send" name="afafaf"/>
        <a class="upload">上传</a>
    </div>
    <input type="button" value="提交jquery" onclick="jqSubmit();">

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

    <script>

        function jqSubmit(){
            //$('#send')[0]
            var file_obj = document.getElementById('send').files[0];

            var fd = new FormData();
            fd.append('username', 'root');
            fd.append('send', file_obj);

            $.ajax({
                url: '/upload_file/',
                type: 'POST',
                data: fd,
                processData:false,// tell jQuery not to process the data
                contentType:false,// tell jQuery not to set contentType
                success: function (arg, a1, a2) {
                    console.log(arg);
                    console.log(a1);
                    console.log(a2);
                }
            })
        }
    </script>
</body>
</html>
templates/upload.html

Iframe进行文件的上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="/upload_file/" enctype="multipart/form-data" target="ifm1">
        <iframe id="iframe"  name="ifm1" style="display: none"></iframe>
        <input type="file" name="send"/>
        <input type="submit" onclick="iframesubmit()" value="Form表单提交"/>
    </form>

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

    <script>     
        function iframesubmit() {
            $("#iframe").load(function () {
                var text = $('#iframe').contents().find('body').text();
                var obj = JSON.parse(text);
                console.log(obj);
            })
        }
    </script>
</body>
</html>
templates/upload.html

 3.图片预览

3.1上传图片后预览

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

def upload_file(request):
    username = request.POST.get('username')
    send = request.FILES.get('send')
    print(username, send)
    import os
    img_path = os.path.join('static/imgs/',send.name)
    with open(img_path, 'wb') as f:
        for item in send.chunks():
            f.write(item)

    ret = {'status': True, 'data': img_path}
    import json
    return HttpResponse(json.dumps(ret))
app01/views.py   #上传到指定文件夹(static/imgs)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
        <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
        <input type="file" name="fafafa"  />
        <input type="submit" onclick="iframeSubmit();" value="Form提交"/>
    </form>
    <div id="preview"></div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        function iframeSubmit(){
            $('#ifm1').load(function(){
                var text = $('#ifm1').contents().find('body').text();
                var obj = JSON.parse(text);
                console.log(obj)
 
                //上传后增加预览模式
                $('#preview').empty();         //清空原有相同文件
                var imgTag = document.createElement('img');   //创建img标签
                imgTag.src = "/" + obj.data;           //路径
                $('#preview').append(imgTag);
            })
        }
    </script>
</body>
</html>

#HTML文件    
templates/upload.html

3.2选择图片后预览

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="form1" method="post" action="/upload_file/" enctype="multipart/form-data" target="ifm1">
        <iframe id="iframe"  name="ifm1" style="display: none"></iframe>
        <input type="file" name="send" onchange="changeupload();"/>
{#        <input type="submit" onclick="iframesubmit()" value="Form表单提交"/>#}
    </form>
    <div id="preview"></div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        function changeupload() {
            $("#iframe").load(function () {
                var text = $('#iframe').contents().find('body').text();
                var obj = JSON.parse(text);
                console.log(obj)

                //上传后增加预览模式
                $('#preview').empty();//清空原有相同文件
                var imgTag = document.createElement('img');//创建img标签
                imgTag.src = "/" + obj.data;//路径
                $('#preview').append(imgTag);
            })
            $('#form1').submit();
        }
    </script>
</body>
</html>

#HTML文件
templates/upload.html
原文地址:https://www.cnblogs.com/dalyday/p/9074806.html