Flask+HTML+Jquery 文件上传下载

HTML 代码:

html 复制代码
<div id="loadingIndicator" style="display:none;">
    <div class="spinner"></div>
</div>  <!-- 请求过程中转圈圈 -->
<form action="" method="post" enctype="multipart/form-data">
    <center>
        <div id="main">
            <div id="un" >
                <input class="inp" type="text" placeholder="请输入手机型号" name="camera_type" id="phone_type">
            </div>
            <div id="pd">
                <input  class="inp" type="text" placeholder="请输入版本号" name="version_num" id="version_num">
            </div>
            <div id="vn">
                <input  class="inp" type="file" placeholder="请选择版本文件" name="versionFile" id="versionFile">
            </div>

            <div class="bt">
                <input class="btns" type="button" value="上&nbsp;&nbsp;&nbsp;传&nbsp;&nbsp;&nbsp;文&nbsp;&nbsp;&nbsp;件" id="btn">
            </div>
        </div>
    </center>
</form>

CSS 代码:

html 复制代码
.inp{
        background-color: #F0F8FF;
        width:30%;
        height:30px;
        line-height:30px;
        margin-top: 10px;
    }
    .btns{
        background-color: lightblue;
        width:30%;
        height:30px;
        line-height:30px;
        margin-top: 10px;
    }
    #inputs{
        width:100%;
        <!--background-color:green;-->
    }
    #loadingIndicator {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    
    .spinner {
        width: 40px;
        height: 40px;
        margin: 0 auto;
        border-radius: 50%;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #3498db;
        animation: spin 2s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

Jquery代码:

javascript 复制代码
$(document).ready(function(){
        console.log("aaa");
        $("#btn").click(function(){
            $('#loadingIndicator').show();
            console.log("click...")
            var formdata= new FormData()
            formdata.append("phone_type",$("#phone_type").val())
            formdata.append("version_num",$("#version_num").val())
            formdata.append("file",$("#versionFile")[0].files[0])
            console.log(formdata)
            $.ajax({
                url:"/uploadfile",
                type:"POST",
                data:formdata,
                processData: false,  // 必须设置为 false 以防止 jQuery 解析 FormData 对象
                contentType: false,  // 必须设置为 false 以允许 FormData 发送原始数据
                success:function (data) {
                    console.log(data)
                    if (data.msg) {
                        alert(data.msg);
                    }
                },
                error: function(xhr, status, error) {
                    alert("上传失败,请重试!, 错误信息:" + error);
                },
                complete: function() {
                    // 隐藏转圈动画
                    $('#loadingIndicator').hide();
                }
            })

        })
    })

Flask部分代码:

python 复制代码
@app.route("/uploadfile",methods=["POST"])
def uploadfile():
    if request.method=="POST":
        login_user=get_loginname()
        if login_user=="guest":
            return jsonify(msg="请登录!",user=login_user)
        file = request.files.get("file")
        print(file)
        if not file:
            return jsonify(msg="请选择文件!",user=login_user)
        camera_type=request.form.get("camera_type")
        if not camera_type:
            return jsonify(msg="请输入相机型号!",user=login_user)
        version_num=request.form.get("version_num")
        if not version_num:
            return jsonify(msg="请输入版本号!",user=login_user)
        print(len(file.read()))
        if len(file.read()) > 1024*1024*256:
            return jsonify(msg=f"文件过大!(camera_type:{camera_type},version:{version_num})",user=login_user)
        file.seek(0)
        try:
            filename = "nvp_fw.bin"
            filepath = os.path.join(uploadrootdir,  camera_type)
            versionfile=os.path.join(filepath, version_num)
            if not os.path.exists(filepath):
                os.makedirs(filepath,mode=777)
            else:
                shutil.rmtree(filepath)
                os.makedirs(filepath,mode=777)
            filefullpath = os.path.join(filepath, filename)
            file.save(filefullpath)
            with open(versionfile, 'w') as f:
                pass
            return jsonify(msg=f"upload success!(camera_type:{camera_type},version:{version_num})",user=login_user)
        except Exception as e:
            print(e)
            return jsonify(msg=f"upload failed!(camera_type:{camera_type},version:{version_num}) (e)",user=login_user)
    return jsonify(msg="upload failed! only support post method")

@app.route("/download/<SNtype>/<file_name>",methods=["GET"])
def download(SNtype,file_name):
    #根据SNType确定文件所在具体位置,刚开始用的是send_from_directory 一直报404,改用send_file
    print("download:",SNtype,file_name)
    rootdir=os.path.join(uploadrootdir,SNtype)
    print(SNtype,file_name)
    print("rootdir:",rootdir)
    filepath=os.path.join(rootdir,file_name)
    if not os.path.exists(filepath):
        return Response("file not exists!")

    return send_file(path_or_file=filepath,as_attachment=True)

开发调试过程中,前端老是报错:SyntaxError: Failed to execute 'querySelectorAll' on 'Element': '*,:x' is not a valid selector 等,无奈直接删除min.js中相应部分代码

相关推荐
鱼馅饼3 小时前
vscode使用系列之快速生成html模板
ide·vscode·html
然我8 小时前
JavaScript的OOP独特之道:从原型继承到class语法
前端·javascript·html
冷凌爱8 小时前
总结HTML中的文本标签
前端·笔记·html
fydw_7158 小时前
生产环境中安装和配置 Nginx 以部署 Flask 应用的详细指南
运维·nginx·flask
灏瀚星空10 小时前
用HTML5 Canvas打造交互式心形粒子动画:从基础到优化实战
前端·html·html5
Teln_小凯12 小时前
Python读取阿里法拍网的html+解决登录cookie
开发语言·python·html
娃哈哈哈哈呀12 小时前
html-pre标签
java·前端·html
Java永无止境12 小时前
Web前端基础:HTML-CSS
java·前端·css·html·javaweb
海的诗篇_15 小时前
前端开发面试题总结-HTML篇
前端·面试·html
Sun_light15 小时前
用原生 HTML/CSS/JS 手把手带你实现一个美观的 To-Do List 待办清单小Demo
前端·css·html