• Django之上传文件


    使用Form表单上传文件

    • upload.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        {#  上传文件的时候必须要在form标签中添加属性 enctype="multipart/form-data"  #}
        <form method="POST" action="/upload/" enctype="multipart/form-data">
    
            <input type="text" name="user" />
            <input type="file" name="img" />
            <input type="submit" />
    
        </form>
    
    </body>
    </html>
    
    
    • views.py
    from django.shortcuts import render
    
    import os
    # Create your views here.
    
    
    def upload(request):
    
        if request.method == "POST":
            user = request.POST.get("user")
            # img = request.POST.get("img")     # 所有提交的文件名
    
            img = request.FILES.get('img')      # 所有提交的文件
    
            img_name = img.name    # 获取文件名
            img_abs_name = os.path.join("static", img_name)
            with open(img_abs_name, "wb") as f:
                for chunk in img.chunks():
                    f.write(chunk)
    
        return render(request, 'upload.html')
    
    

    上传完之后可以通过链接 “http://127.0.0.1:8000/static/文件名” 打开图片

    使用js原生XMLHttpRequest对象进行ajax上传文件

    • upload.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <input type="text" id="user" name="user" />
        <input type="file" id="img" name="img" />
        <input type="button" value="上传图片" onclick="uploadFile1();"/>
    
        <script>
    
             // 使用原生的 XMLHttpRequest 上传图片
            function uploadFile1() {
                var form = new FormData();
                form.append("user", document.getElementById("user").value);
    
                // 获取文件对象
                var fileObj = document.getElementById("img").files[0];
                form.append("img", fileObj);
    
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4){
                        // 已经接受到全部响应数据,执行以下操作
                        var data = xhr.responseText;
                        console.log(data);
                    }
                };
    
                xhr.open("POST", "/upload/", true);
                xhr.send(form);
            }
        </script>
    
    </body>
    </html>
    
    
    • views.py
    from django.shortcuts import render
    from django.shortcuts import HttpResponse
    
    import os
    # Create your views here.
    
    
    def upload(request):
    
        if request.method == "POST":
            user = request.POST.get("user")
            # img = request.POST.get("img")     # 所有提交的文件名
    
            img = request.FILES.get('img')      # 所有提交的文件
    
            img_name = img.name
            img_abs_name = os.path.join("static", img_name)
            with open(img_abs_name, "wb") as f:
                for chunk in img.chunks():
                    f.write(chunk)
    
            return HttpResponse("ok")
    
        return render(request, 'upload.html')
    

    使用jQuery 的ajax上传文件

    该方法需要借助js原生的FormData()将数据封装到该对象中,并且不支持低版本的浏览器,例如ie5、ie6

    • upload.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <input type="text" id="user" name="user" />
        <input type="file" id="img" name="img"  />
        <input type="button" value="上传图片" onclick="jQueryAjax();"/>
    
        <script src="/static/jquery/jquery-1.12.4.js"></script>
        <script>
    
            function jQueryAjax() {
    
                // 获取文件对象
                var fileObj = $("#img")[0].files[0]; 
    
                // 创建FormData对象
                var form = new FormData();
                
                // 将数据封装到对象中
                form.append("img", fileObj);
                form.append("user", "aa");
    
                $.ajax({
                    type: "POST",
                    url: "/upload/",
                    data: form,
                    processData: false,    
                    contentType: false,    # 不设置请求头
                    sucess: function (arg) {
                        console.log(arg);
                    }
                })
            }
        </script>
    
    </body>
    </html>
    
    
    • views.py
    from django.shortcuts import render
    from django.shortcuts import HttpResponse
    
    import os
    import json
    # Create your views here.
    
    
    def upload(request):
    
        if request.method == "POST":
            user = request.POST.get("user")
            # img = request.POST.get("img")     # 所有提交的文件名
    
            img = request.FILES.get('img')      # 所有提交的文件
    
            img_name = img.name
            img_abs_name = os.path.join("static", img_name)
            print(img_abs_name)
            with open(img_abs_name, "wb") as f:
                for chunk in img.chunks():
                    f.write(chunk)
    
            return HttpResponse("ok")
    
        return render(request, 'upload.html')
    

    使用jQuery 的ajax + iframe 解决浏览器兼容性的问题

    • upload1.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
    
            #container img{
                 100px;
                height: 100px;
    
            }
        </style>
    </head>
    <body>
    
        <iframe id="my_iframe" name="my_iframe" style="display:none" src="" ></iframe>
    
        <form id="fo" method="POST" action="/upload1/" enctype="multipart/form-data">
            <input type="text" id="user" name="user" />
            <input type="file" id="img" name="img" onchange="uploadFile();" />
            <input type="submit">
    
        </form>
    
        <div id="container">
    
        </div>
    
        <script src="/static/jquery/jquery-1.12.4.js"></script>
        <script>
    
            function uploadFile() {
                $("#container").find("img").remove();
                document.getElementById("my_iframe").onload = callback;
                document.getElementById("fo").target = "my_iframe";
                document.getElementById("fo").submit();
            }
    
            function callback() {
                
                // 想获取iframe中的标签必须使用.contents来获取
                var text = $("#my_iframe").contents().find('body').text();
                var json_data = JSON.parse(text);
    
                if (json_data.status){
                    // 上传成功
                    // 生成img标签,预览刚才上传成功的图片
    
                    var tag = document.createElement("img");
                    tag.src = "/" + json_data.data;
                    tag.className = "img";
                    $("#container").append(tag);
                }else{
                    alert(json_data.error);
                }
            }
    
        </script>
    </body>
    </html>
    
    
    • views.py
    from django.shortcuts import render
    from django.shortcuts import HttpResponse
    
    import os
    import json
    # Create your views here.
    
    def upload1(request):
        if request.method == "POST":
            ret = {
                "status": False,
                "data": None,
                "error": None,
            }
    
            try:
                img = request.FILES.get("img")
                img_name = img.name
                img_abs_name = os.path.join("static", img_name)
                print(img_abs_name)
                with open(img_abs_name, "wb") as f:
                    for chunk in img.chunks():
                        f.write(chunk)
                ret["status"] = True
                ret["data"] = img_abs_name
    
            except Exception as e:
                ret["error"] = str(e)
    
            return HttpResponse(json.dumps(ret))
    
        return render(request, "upload1.html")
    
  • 相关阅读:
    03:矩形分割 (二分)
    09:膨胀的木棍 (二分+角度计算)
    A Cubic number and A Cubic Number (二分) HDU
    B
    08:不重复地输出数 (set)
    10:河中跳房子 (二分)
    07:和为给定数 (二分)
    04:网线主管 (二分)
    河中跳房子
    010:输出前k大的数
  • 原文地址:https://www.cnblogs.com/CongZhang/p/5905021.html
Copyright © 2020-2023  润新知