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()將數據封裝到該對象中,而且不支持低版本的瀏覽器,例如ie五、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{
            width: 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")
相關文章
相關標籤/搜索