matinal:python 上传多个文件

2023-10-14 15:39:13 浏览数 (1)

后台

代码语言:javascript复制
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))

前端

代码语言:javascript复制
<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" οnsubmit="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>

0 人点赞