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

猜你喜欢

转载自www.cnblogs.com/Mengchangxin/p/9951472.html