layui 上传文件进度条显示功能

页面

1.jsp里面中

 <div class="layui-form-item">
        <label class="layui-form-label required">特定excel</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn layui-btn-normal" id="chosse">选择文档</button>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">上传</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="btnUpload">开始上传</button>
        </div>
    </div>
    <!--弹出进度条-->
    <div id="uploadLoadingDiv" style="display: none;">
        <div class="layui-progress" lay-showpercent="true" lay-filter="js_upload_progress" style="margin: 10px;margin-top: 20px">
            <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
        </div>
    </div>

2.js中

 layui.use(['form','element', 'upload'], function() {
        var $ = layui.jquery,
            upload = layui.upload,
            form=layui.form
            layer = layui.layer,
            element = layui.element;
        element.init();
        form.render();
        //创建监听函数
        var xhrOnProgress=function(fun) {
            xhrOnProgress.onprogress = fun; //绑定监听
            //使用闭包实现监听绑
            return function() {
                //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
                var xhr = $.ajaxSettings.xhr();
                //判断监听函数是否为函数
                if (typeof xhrOnProgress.onprogress !== 'function')
                    return xhr;
                //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
                if (xhrOnProgress.onprogress && xhr.upload) {
                    xhr.upload.onprogress = xhrOnProgress.onprogress;
                }
                return xhr;
            }
        }
        upload.render({
            elem: '#chosse'
            ,url: '${baseurl}/****/uploadFiles.html'// 自己的上传接口路径
            ,size:"2048"
            ,auto: false  //auto 参数必须设置为false
            ,bindAction: '#btnUpload'    //auto为false时,点击触发上传
            ,multiple: false
            ,field: 'file'
            ,accept: 'file'
            ,exts:'xlsx'
            ,choose: function(obj){  //上传前选择回调方法
                obj.preview(function(index, file, result){
                    $('#title').attr('value', file.name);
                });
                $("#btnUpload").show();
            }
            ,before:function(){
                element.progress('js_upload_progress', '0%');//设置页面进度条
                layer.open({
                    type: 1,
                    title: '上传进度',
                    closeBtn: 1, //不显示关闭按钮
                    area: ['300px', '90px'],
                    shadeClose: false, //开启遮罩关闭
                    content: $("#uploadLoadingDiv").html(),
                    offset: '100px'
                });
            }
            ,xhr:xhrOnProgress
            ,progress:function(value){//上传进度回调 value进度值
                element.progress('js_upload_progress', value+'%');//设置页面进度条
            },
            //普通文件
            done: function (res) {
                layer.close(layer.index);
                layer.msg(res.msg,{
                    icon : 1,
                    time:1500
                },function () {
                    if (res.success == true){
                        $('#filepath').attr('value', res.obj);
                        $("#btnUpload").hide();
                    }
                });
            },
            error: function (index, upload) {
                layer.alert("上传失败,请重新上传."+index);
                console.error(index);
                return false;
            }
        });
    });

3.需要引入的js文件

自己到官网上去下载需要的JS文件,下面这两个必须要引入的。

<script src="${baseurl}/layui/lib/layui/layui.js" charset="utf-8"></script>
<script src="${baseurl}/layui/js/lay-config.js?v=1.0.4" charset="utf-8"></script>

java 代码

上传代码

AjaxJson 自己写的结果集。
Constants.HOMEPATH+Constants.UPLOAD_PER_FILE 自己定义的路径

 @RequestMapping("/uploadFiles")
    @ResponseBody
    public AjaxJson uploadFiles(HttpServletRequest request){
        AjaxJson json = new AjaxJson();
        log.info("每日信息(一手)---进入上传.......");
        try {
            String tempPath = Constants.HOMEPATH+Constants.UPLOAD_PER_FILE+"/"+System.currentTimeMillis();
            try {
                String path = FileUtil.copyFileByExcel(request, tempPath);
                path = path.replace(Constants.HOMEPATH,"");
                json.setMsg("上传成功");
                json.setObj(path);
                json.setSuccess(true);
            } catch (Exception e) {
                json.setSuccess(false);
                json.setMsg(e.toString());
                e.printStackTrace();
            }
        }catch (Exception e) {
            json.setMsg(e.toString());
            json.setSuccess(false);
            log.info("每日信息(一手)------"+e.toString());
            e.printStackTrace();
        }
        return json;
    }
public static String copyFileByExcel(HttpServletRequest request, String filePath)
            throws IOException {
        String fileName = "";
        // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取上传文件对象
                MultipartFile mf = entity.getValue();
                if (!mf.isEmpty()) {
                    fileName += mf.getName() + mf.getOriginalFilename();
                    fileName = fileName.replace("img", "");
                    //把图片名称改为cover
                    int index = fileName.indexOf(".");
                    String s1 = fileName.substring(0,index);
                    fileName = fileName.replace(s1, "BJ"+System.currentTimeMillis());
                    // 拼接后台文件名称
                    // 文件保存全路径
                    String savePath = filePath +"/"+ fileName;
                    File savefile = new File(savePath);
                    // 判断文件保存是否存在
                    if (savefile.getParentFile() != null || !savefile.getParentFile().isDirectory()) {
                        // 创建文件
                        savefile.getParentFile().mkdirs();
                    }
                    try {
                        mf.transferTo(savefile);
                        //返回是全部路径
                        return savePath;
                    } catch (IOException e) {
                        throw new IOException("上传失败--" + e.getMessage());
                    }
                }
            }
        }else {
            throw new IOException("上传文件请求头信息错误");
        }
        return null;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperChen12356

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值