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

相关推荐
anOnion2 天前
构建无障碍组件之Radio group pattern
前端·html·交互设计
前端Hardy2 天前
HTML&CSS&JS:丝滑无卡顿的明暗主题切换
javascript·css·html
前端Hardy3 天前
HTML&CSS&JS:基于定位的实时天气卡片
javascript·css·html
前端Hardy3 天前
HTML&CSS:纯CSS实现随机转盘抽奖机——无JS,全靠现代CSS黑科技!
css·html
DeathGhost3 天前
分享URL地址到微信朋友圈没有缩略图?
前端·html
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_19632884754 天前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask
计算机专业码农一枚4 天前
Python-flask框架基于推荐算法的在线课程推荐系统设计与实现-Pycharm django
python·flask·推荐算法
前端Hardy4 天前
HTML&CSS:高颜值产品卡片页面,支持主题切换
css·html