• python 上传多文件


    后台

    import json
    from django.shortcuts import render,HttpResponse,HttpResponseRedirect
    import os
    import json
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    def upload(request):
    
        if request.method == 'GET':
            return render(request, 'form.html')
        else:
            file_name = request.POST.get('user')
            pwd = request.POST.get('pwd')
            file_obj = request.FILES.get('file')
    
            f = open(os.path.join(BASE_DIR, 'static','images',file_name+'.png'), 'wb')
            # print(file_obj, type(file_obj))
    
            for chunk in file_obj.chunks():
                f.write(chunk)
                f.close()
    
        msg = {
            'status':True,
            'msg':'上传成功',
            'fileName':file_name,
            'pwd':pwd
        }
        return HttpResponse(json.dumps(msg))
    
    def morefiles(request):
        if request.method == 'GET':
            return render(request, 'morefile.html')
        else:
            file_name = request.POST.get('userName')
            pwd = request.POST.get('password')
            #获取单个文件
            # file_obj = request.FILES.get('files')
            print(file_name,pwd)
            #获取多个文件对象
            files = request.FILES.getlist('files')
            print(files)
            for f in files:
                
                destination = open(os.path.join(BASE_DIR, 'static','images',f.name),'wb+')
                for chunk in f.chunks():
                    destination.write(chunk)
                destination.close()
    
            msg = {
                'status':200,
                'msg':'上传成功',
                # 'fileName':file_name,
                # 'pwd':pwd
            }
            return HttpResponse(json.dumps(msg))
    

     前端

    <html>
    <head>
        <title>login test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="ajax方式">
    <!--    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>-->
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.3.min.js"></script>
        <script type="text/javascript">
            $(function () {
                let fileList = [];
                let files = $("#files");
                files.on("change", function (event) {
                    for (var i = 0; i < files[0].files.length; i++) {
                        fileList.push(files[0].files[i]);
                    }
                    console.log(fileList)
                });
    
                $("#login").click(function () {
                    let formData = new FormData();
                    fileList.forEach(function (file,index) {
                        formData.append('files', file, file.name);
                    })
                    formData.append("userName",$("#userName").val())
                    formData.append("password",$("#pwd").val())
    
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "/morefiles/" ,//url
                        data: formData,
                        contentType:false,
                        processData:false,
                        success: function (result) {
                            console.log(result);//打印服务端返回的数据(调试用)
                            if (result.resultCode == 200) {
                                alert("SUCCESS");
                            }
                            ;
                        },
                        error : function() {
                            alert("异常!");
                        }
                    });
                })
            })
    
        </script>
    </head>
    <body>
    <div id="form-div">
        <form id="form1" onsubmit="return false" action="/" method="post" enctype="multipart/form-data">
            <p>用户名:<input id="userName" name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p>
            <p>密 码:<input id="pwd" name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
            <p>附件: <input id="files" type="file" name="files" multiple="multiple"></p>
            <p><input id="login" type="button" value="登录" > <input type="reset" value="重置"></p>
        </form>
    </div>
    </body>
    </html>
    

      

  • 相关阅读:
    关于项目架构设计的一些规范
    Repository 返回 IQueryable?还是 IEnumerable?
    EntityFramework DbContext 线程安全
    ASP.NET 页面禁止被 iframe 框架引用
    2015-写给明年现在的自己
    RESTful API URI 设计: 查询(Query)和标识(Identify)
    深入探讨:标签(Tag)的各种设计方案
    RESTful API URI 设计: 判断资源是否存在?
    iPhone 6/plus iOS Safari fieldset border 边框消失
    追根溯源:EntityFramework 实体的状态变化
  • 原文地址:https://www.cnblogs.com/qq735675958/p/11403932.html
Copyright © 2020-2023  润新知