ifram+form方式实现文件、图片上传、预览

1、前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .btn{
            display: inline-block;
            padding: 5px 10px;
            background-color: coral;
            color: white;
        }
    </style>
</head>
<body>

    <iframe style="display: none" id="iframe1" name="ifra1"></iframe>
    <form id="fm1" action="/upload_img.html" method="POST" enctype="multipart/form-data" target="ifra1">
        <input type="file" name="k1" onchange="uploadFile();" />
    </form>
    <h3>预览</h3>
    <div id="preview">
    </div>
    <script src="/static/js/jquery-3.1.1.js"></script>
    <script>
         //文件上传控件绑定onchange事件,当有文件上传就触发表单提交
        function uploadFile() {
            document.getElementById('iframe1').onload = reloadIframe1;
            document.getElementById('fm1').submit();
        }

        //取得iframe控件的返回值,并将值取出进行json反序列化,
        function reloadIframe1() {
            var content = this.contentWindow.document.body.innerHTML;
            var obj = JSON.parse(content);

            //创建img控件,并将远端的图片地址赋予image。
            var tag = document.createElement('img');
            tag.src = obj.data;
            $('#preview').empty().append(tag);
        }
    </script>
</body>
</html>   

2、后端代码

def upload_img(request):
    ret={'status':True,'data':None}
    obj = request.FILES.get('k1')
    print(obj)
    file_path = os.path.join('static',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))
原文地址:https://www.cnblogs.com/xiaoqianghuihui/p/7152055.html