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>

 

posted @ 2019-03-09 16:00  烛爻  阅读(626)  评论(0编辑  收藏  举报