• django 制作上传图片并预览的效果


    views.py

    import json, os, uuid
    
    def upload(request):
        return render(request, 'upload.html')
    
    
    def upload_file(request):
        nid = str(uuid.uuid4())  # 加一个随机码防止上传的文件重名
        ret = {'status': True, 'data': None, 'message': None}
        obj = request.FILES.get('k3')
        file_path = os.path.join('static', nid + obj.name)
        f = open(file_path, 'wb')  # 把文件上传到静态文件夹下
        for line in obj.chunks():
            f.write(line)
        f.close()
        # 把上传来的文件路径传给前端,让前端访问来显示上传的图片以达到预览的效果
        ret['data'] = file_path
        return HttpResponse(json.dumps(ret))

    upload.html

    <body>
        <iframe style="display: none" id="iframe1" name="ifra1" ></iframe>
        <form id="fm1" action="/upload_file/" method="post" target="ifra1" enctype="multipart/form-data">
            <input type="file" name="k3" onchange="uploadFile();">  //绑定事件,让其选择完图片后就上传并预览
        </form>
        <h3>预览</h3>
        <div id="preview">
    
        </div>
    
    <script src="/static/js/jquery-3.3.1.js"></script>
    <script>
        function uploadFile() {
            document.getElementById('iframe1').onload = reloadIframe1;
            document.getElementById('fm1').submit()
        }
    
        function reloadIframe1() { //相当于回调函数,当数据返回的时候执行
            //this等于当前标签(iframe)
            var content = this.contentWindow.document.body.innerText;
            var obj = JSON.parse(content);
            var tag = document.createElement('img');
            tag.src = '/'+obj.data;
            $('#preview').empty().append(tag)  //限制了只在预览区显示一张图片
        }
    </script>
    </body>
  • 相关阅读:
    转载Crazybingo的文章: 第三章 创造平台——Quartus II 11.0 套件安装指南
    Can't launch the ModelSim-Altera software
    一种简单的ADV7842调试视频pixel_cnt/line的办法.
    调试ADV7842的点滴 之 hdmi
    沿检测使能,时钟同步化
    global clock network
    捡到篮子里边的都是菜
    (转)时序分析基本公式
    Spring中的AOP(一)
    AOP的概念
  • 原文地址:https://www.cnblogs.com/zq8421/p/10501559.html
Copyright © 2020-2023  润新知