1. 程式人生 > >django----檔案上傳

django----檔案上傳

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #img img{
            height: 200px;
            width: 200px;
        }
    </style>
</head>
<body>
<h1>普通檔案上傳</h1>
<div>
    <form method="
POST" action="/upload.html" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="fafafa"> <input type="submit" value="上傳"> </form> </div> <h1>AJAX檔案上傳</h1> <div> <input type="file" id="img"> <input type="
button" value="ajax上傳" onclick="Upload()" /> </div> <hr/> <div> <h1>測試功能IFRAME</h1> <input type="text" id="url"> <input type="button" value="點我" onclick="iframeChange();"> <iframe src="" frameborder="1" id="ifr" ></iframe> <hr/> <h1>基於iframe實現檔案上傳功能</h1> <form method="
POST" action="/upload.html" target="iframe_1"> <iframe src="" frameborder="1" name="iframe_1" id="iframe_1" onload="LoadIframe();"></iframe> <input type="text" name="user"> <input type="file" name="fafafa"> <input type="submit" value="上傳"> </form> </div> <div id="img"> <H1>圖片列表</H1> {% for item in url_list %} <img src="\{{ item.imgsrc }}"> {% endfor %} </div> <script src="/static/jq/jquery-3.3.1.js"></script> <script> function Upload() { var dic=new FormData(); dic.append('user','v1'); dic.append('fafafa',document.getElementById('img').files[0]);//獲取當前檔案的第一個物件 var xml=new XMLHttpRequest(); xml.open('POST','/upload.html',true);//用非同步的方式//傳檔案 不需要請求頭 xml.send(dic); } function iframeChange() { var url=$("#url").val(); $("#ifr").attr("src",url); } function LoadIframe() { console.log(111); //獲取iframe內部的內容 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; $("#img").append(img) } } </script> </body> </html>
View Code