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

相关推荐
志尊宝1 天前
Vue3 零基础每日笔记(055):组件里正确使用 store——storeToRefs 解构与 $patch 批量修改
笔记·vue·html·前端开发·软件开发
吴声子夜歌1 天前
HTML——看似普通的元素的背后(<a>标签)
html
IMPYLH1 天前
HTML 的 <style> 元素
前端·html
刃神太酷啦1 天前
前端入门第一课:HTML 基础语法 + 常用标签 + 实战全解
服务器·c语言·前端·javascript·css·c++·html
IMPYLH1 天前
HTML 的 <strong> 元素
前端·html
开开心心就好1 天前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
我命由我123452 天前
CSS - CSS 媒体查询 orientation
前端·javascript·css·html·css3·html5·js
咩咩啃树皮2 天前
ES6 Set 核心特点 + 最简数组去重
前端·javascript·html
zhanghaha13142 天前
HTML系列教程:18_HTML / CSS 颜色零基础详解
css·html·tensorflow
Aaswk2 天前
从 HTML/CSS/JS 到 Vue + Axios 的一篇实战笔记
前端·css·vue.js·html