zoukankan      html  css  js  c++  java
  • 利用iframe和form上传和预览图片

    URL文件

    from django.contrib import admin
    from django.urls import path
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
    
        path('upload.html/', views.upload),
        path('upload_img.html/', views.upload_img),
    ]

    views文件

    from django.shortcuts import render,HttpResponse
    import json
    # Create your views here.
    
    
    
    def upload(request):
    
        return render(request,'upload.html')
    
    def upload_img(request):
        import os
        import uuid
    
        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))

    html文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .btn{
                display: inline-block;
                padding: 5px 10px;
                color: orangered;
            }
        </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="k3" onchange="uploadFile()"/>
    
        </form>
    
    
         <h3>预览</h3>
        <div id="prevl">
    
        </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() {
                var content = this.contentWindow.document.body.innerHTML;
                var obj = JSON.parse(content);
                console.log(obj.data);
                var tag = document.createElement('img');
                tag.src='/'+obj.data;
                $('#prevl').empty().append(tag)
    
            }
    
        </script>
    
    
    </body>
    </html>
  • 相关阅读:
    JavaScript获取键盘事件
    Java 虚拟机的内存结构
    Java 实现 Http 请求工具类
    HTML5之FileReader文件读取接口
    使用 PLSQL 连接 Oracle9i 数据库
    使用 Navicate 连接 Oracle9i 数据库
    Eclipse 刚检出的项目 Build path 的时候提示 No action available
    Eclipse 中 Debug 调试 java 代码一直报 Source not found
    mongodb 客户端工具
    spring 国际化
  • 原文地址:https://www.cnblogs.com/lhqlhq/p/9202874.html
Copyright © 2011-2022 走看看