Django学习之文件上传三种方式

一、From表单上传

class Img(models.Model):
    path = models.CharField(max_length=128)
models.py
def upload(request):
    if request.method == "GET":
        img_list = Img.objects.all()
        return render(request,"upload.html",{'img_list': img_list})
    elif request.method == "POST":
        #对于上传的文件需要通过request.FILES["txt"]或者request.FILES.get("txt", None)来访问,上传的文件是保存在FILES这个字典中的
        obj = request.FILES.get('img',None)
        if not obj:
            return HttpResponse("no files for upload!")
        file_path =  os.path.join('static','upload',obj.name)
        f = open(os.path.join('app01','static','upload',obj.name), 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
        Img.objects.create(path=file_path)
        return redirect('/upload')
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="img" />
        <input type="submit" value="提交" />
    </form>

    


    <div>
        {% for item in img_list %}
            <img style="height: 200px;width: 200px;" src="/{{ item.path }}" />
        {% endfor %}
    </div>





</body>
</html>
upload.html

 二、ajax上传

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

     <style>
        .container img{
            width: 200px;
            height: 200px;
        }
    </style>

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

    <input type="file" id="img" />
    <input type="button" value="提交XML" onclick="UploadXML()" />
    <input type="button" value="提交JQ" onclick="Uploadjq()" />

 <h1>图片列表</h1>
    <div class="container" id="imgs">
        {% for img in img_list %}
            <img src="/{{ img.path }}">
        {% endfor %}
    </div>



<script>
    //原生ajax  上传文件需要使用FormData. FormData用来获取表单数据,方便进行提交数据.添加数据使用append方法
     function UploadXML() {
            var dic = new FormData();
            dic.append('img', document.getElementById('img').files[0]);
            var xml = new XMLHttpRequest();
            xml.open('post', '/upload', true);
            xml.onreadystatechange = function () {
                if(xml.readyState == 4){
                    var obj = JSON.parse(xml.responseText);
                    if(obj.status){
                        var img = document.createElement('img');
                        img.src = "/" + obj.path;
                        document.getElementById("imgs").appendChild(img);
                    }
                }
            };
            xml.send(dic);
        }

     //jquery ajax
      function Uploadjq() {
            var dic = new FormData();
            dic.append('img', document.getElementById('img').files[0]);
            $.ajax({
                url: '/upload',
                type: 'POST',
                data: dic,
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,  //  告诉jQuery不要去设置Content-Type请求头   一定要设置jquery中不处理数据,不设置内容类型,否则报错
                dataType: 'JSON',
                success: function (arg) { //成功回调
                    if (arg.status){
                        var img = document.createElement('img');
                        img.src = "/" + arg.path;
                        $('#imgs').append(img); //把图片路径添加到img标签的src
                    }
                }
            })
        }

</script>


</body>
</html>
upload.html
def upload(request):
    if request.method == "GET":
        img_list = Img.objects.all()
        return render(request,"upload.html",{'img_list': img_list})
    elif request.method == "POST":
        #对于上传的文件需要通过request.FILES["txt"]或者request.FILES.get("txt", None)来访问,上传的文件是保存在FILES这个字典中的
        obj = request.FILES.get('img',None)
        if not obj:
            return HttpResponse("no files for upload!")
        file_path =  os.path.join('static','upload',obj.name)
        f = open(os.path.join('app01','static','upload',obj.name), 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
        Img.objects.create(path=file_path)
        #return redirect('/upload')
        #通过ajax上传处理
        ret = {'status': True, 'path': file_path}
        return HttpResponse(json.dumps(ret))
views.py
通常我们提交(使用submit button)时,会把form中的所有表格元素的name与value组成一个queryString,提交到后台。这用jQuery的方法来说,就是serialize。通过$('#postForm').serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。
但是上述方式,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。
不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。

创建FormData对象:var fdata = new FormData();
添加键值对:fdata.append("url", "http://www.baidu.com/");
注: 通过 FormData.append()方法赋给字段的值若是数字会被自动转换为字符(字段的值可以是一个Blob对象,一个File对象,或者一个字符串,剩下其他类型的值都会被自动转换成字符串).

其他使用:
FormData.delete:将一对键和值从 FormData 对象中删除。
FormData.get:返回给定键的第一个值
Formdata学习

 三、基于form表单和iframe自己实现ajax请求实现文件上传

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

     <style>
        .container img{
            width: 200px;
            height: 200px;
        }
    </style>

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

     <h1>测试Iframe功能</h1>
    <iframe  id="ifr" src=""></iframe>
    <input type="text" id="url" />
    <input type="button" value="点我" onclick="iframeChange();" />

    <hr/>
    <h1>基于iframe实现form提交</h1>
    <form action="/upload.html" method="post" target="iframe_1" enctype="multipart/form-data">
        <iframe  id="iframe_1" name="iframe_1" src="" onload="loadIframe();"></iframe>
        <input type="file" name="img" />
        <input type="submit" />
    </form>

 <h1>图片列表</h1>
    <div class="container" id="imgs">
        {% for img in img_list %}
            <img src="/{{ img.path }}">
        {% endfor %}
    </div>



<script>

    function  iframeChange() {
            var url = $('#url').val();
            $('#ifr').attr('src', url);
        }

   function loadIframe() {

            // 获取iframe内部的内容  {"status": true, "path": "static\\upload\\719d372b2b447fea0cb688887f51f354.jpg"}
            var str_json = $('#iframe_1').contents().find('body').text();
            var obj = JSON.parse(str_json);
            if (obj.status){
                var img = document.createElement('img');
                img.src = "/" + obj.path;
                $('#imgs').append(img);
            }
        }

</script>


</body>
</html>
upload.html
def upload(request):
    if request.method == "GET":
        img_list = Img.objects.all()
        return render(request,"upload.html",{'img_list': img_list})
    elif request.method == "POST":
        #对于上传的文件需要通过request.FILES["txt"]或者request.FILES.get("txt", None)来访问,上传的文件是保存在FILES这个字典中的
        obj = request.FILES.get('img',None)
        if not obj:
            return HttpResponse("no files for upload!")
        file_path =  os.path.join('static','upload',obj.name)
        f = open(os.path.join('app01','static','upload',obj.name), 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
        Img.objects.create(path=file_path)
        #return redirect('/upload')
        #通过ajax上传处理
        ret = {'status': True, 'path': file_path}
        return HttpResponse(json.dumps(ret))
views.py

 

posted @ 2019-11-06 17:26  泉love水  阅读(243)  评论(0编辑  收藏  举报