Flask+layui打造带进度条的文件上传

layui的上传默认是没有添加上传的监听,我们需要在layui的upload.js模块中先添加上传监听事件的句柄

找到static\layui\lay\modules下的upload.js文件,为了方便添加代码,我将里面压缩的样式格式化了下,然后添加以下代码

01.
xhr:function () {
02.
    var newXhr = i.ajaxSettings.xhr();
03.
    // 给xhr的upload添加progress的监听
04.
    newXhr.upload.addEventListener('progress' , function (e) {
05.
        var percent = Math.floor(e.loaded / e.total * 100); //计算出进度
06.
        typeof l.progress === 'function' && l.progress(e , percent); // 传递给upload的progress回调
07.
    });
08.
    return newXhr;
09.
},

改好是这样的

{CE684A4B-8A91-42CB-B415-493C72EC19AB}_20190510114705.jpg

改完了以后你可以选择把这个js文件压缩回原来的样子

然后最重要的环节就做完了,我们来看看模板代码和flask上传方法

html代码如下

01.
{% extends "web/layout.html" %}
02.
{% block title %}
03.
苏老博客
04.
{% endblock %}
05.
{% block content %}
06.
<div class="layui-container">
07.
    <div class="layui-form">
08.
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
09.
            <legend>文件上传,上传进度条</legend>
10.
        </fieldset>
11.
        <div class="layui-form-item">
12.
            <div class="layui-upload" style="margin-top: 10px;">
13.
                <button type="button" class="layui-btn layui-btn-normal" id="select">选择文件</button>
14.
                <button type="button" class="layui-btn" id="upload">开始上传</button>
15.
            </div>
16.
        </div>
17.
    </div>
18.
    <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="progressBar">
19.
        <div class="layui-progress-bar layui-bg-green" lay-percent="0%"></div>
20.
    </div>
21.
</div>
22.
<script>
23.
layui.use(['element','layer','upload','jquery'], function(){
24.
    var element = layui.element
25.
    ,layer = layui.layer
26.
    ,upload = layui.upload
27.
    ,$ = layui.jquery;
28.
    upload.render({
29.
    elem: '#select'
30.
    ,accept: 'file'
31.
    ,exts: 'zip|rar|7z|tar|gz|xz|gzip'
32.
    ,url: '{{ url_for("web.upload") }}'
33.
    ,auto: false
34.
    ,multiple: true
35.
    ,bindAction: '#upload'
36.
    ,progress: function(e , percent) {
37.
element.progress('progressBar',percent  + '%');
38.
}
39.
    ,done: function(res){
40.
      layer.msg("上传成功")
41.
    }
42.
    ,error: function(index, upload){
43.
      layer.alert("上传失败")
44.
    }
45.
  });
46.
});
47.
</script>
48.
{% endblock %}

由于upload方法添加了监听事件,我们可以通过绑定的dom类来修改属性的值了

然后是我的上传方法

01.
#!/usr/bin/python3
02.
#coding:utf-8
03.
from flask import Flask,jsonify,request
04.
from werkzeug.utils import secure_filename
05.
from app.web import web
06.
import os
07.
import time
08.
#上传函数
09.
@web.route('/upload', methods=['POST', 'GET'])
10.
def upload():
11.
    if request.method == "POST":
12.
        #获取上传文件对象
13.
        f = request.files['file']
14.
        #今日附件目录
15.
        attchment_dir = time.strftime("%Y/%m/", time.localtime())
16.
        upload_path = os.path.join("app/upload/", attchment_dir)
17.
        #判断附件目录是否存在
18.
        isExist = os.path.exists(upload_path)
19.
        if not isExist:
20.
            #不存在就创建
21.
            os.makedirs(upload_path, 0o777)
22.
        #拼接文件相对路径
23.
        src = os.path.join(upload_path + secure_filename(f.filename))
24.
        f.save(src)
25.
        datas = {
26.
            "code":0,
27.
            "msg":"",
28.
            "data":{
29.
                "src":src
30.
            }
31.
        }
32.
        return jsonify(datas)

最后上传下效果图

{FCC6261C-15AD-4AE1-A051-F27488F2994B}_20190510115048.jpg

{3D24F313-8E28-49A4-AE7D-292C1C69AAC0}_20190510115058.jpg

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/665

评论列表