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中相应部分代码

相关推荐
weixin_BYSJ19877 小时前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
杨超越luckly8 小时前
Agent应用指南:13年与13线——武汉地铁进化史
数据分析·html·agent·可视化·地铁客流
葡萄城技术团队11 小时前
HTML元素单元格:用自定义 CellType 扩展 SpreadJS 的显示能力
前端·javascript·html
逝水无殇11 小时前
HTML 属性(HTML Attributes)详解
开发语言·前端·html·html5
暮暮祈安1 天前
Celery 新手入门指南
java·数据库·python·flask·httpx
码农学院1 天前
2026年生成式搜索引擎优化对服务业本地化获客帮助的数字化转型路径
前端·搜索引擎·html
小大宇1 天前
python flask框架 SSE流式返回、跨域、报错
开发语言·python·flask
编码者卢布1 天前
【Azure Policy】Policy修正任务为Azure资源添加诊断日志报错问题的调查
microsoft·flask·azure
浮江雾1 天前
Flutter第十六节-----路由管理(2)
android·开发语言·前端·javascript·flutter·html
shandianchengzi1 天前
【开源工具】我做了一个周深歌曲淘汰赛生成器:挑选 128 首歌 PK,选出你的年度 TOP1
html·音乐·网页·世界杯