上传下载 原生js

加载的部分layui插件

.file-box {
    width: 76px;
    display: inline-block;
    position: relative;
    overflow: hidden;
    background-color: #009688;
    color: #fff;
    white-space: nowrap;
    text-align: center;
    font-size: 14px;
    border: none;
    border-radius: 2px;
    height: 32px;
    line-height: 32px;
    padding: 0 10px;
    outline: 0;
    -webkit-appearance: none;
    transition: all .3s;
    -webkit-transition: all .3s;
    box-sizing: border-box;
    margin-left: 20px;
}

.fileBtn {
    z-index: 10;
    width: 76px;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    outline: none;
    background-color: transparent;
    filter: alpha(opacity=0);
    -moz-opacity: 0;
    -khtml-opacity: 0;
    opacity: 0;
}

.fileUploadList {
    width: 100%;
    height: auto;
    color: #444;
    margin-top: 10px;
}

.upLoadFile {
    width: 100%;
    height: 40px;
    line-height: 40px;
    box-sizing: border-box;
    padding: 0 20px;
    background-color: rgb(212, 237, 249);
}

.upLoadFile>div {
    display: inline-block;
}

.upLoadFile>span {
    width: 40px;
    display: inline-block;
}

.fileName {
    margin-right: 30px;
    width: 300px;
}

.fileProcess {
    margin: 0 30px;
}
                <div class="file-box">
                    <input type="file" class="fileBtn" title="请选择文件" id="selectFile" /> 上传文件
                </div>
                <div class="fileUploadList" id="fileUploadList">

                </div>
  //上传文件
    var fileInfo = document.getElementById("selectFile");
    var flieID = ""; //文件id
    var fileSeccess = ''; //上传成功返回参数
    $(".file-box").on("change", ".fileBtn", function(e) {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        flieID = "" + year + month + day + hour + minute + second;
        //文件大小计算
        var flieSize = Math.round(fileInfo.files[0].size / 1024);
        if (flieSize > 1024) {
            flieSize = Math.round(flieSize / 1024) + 'M';
        } else {
            flieSize = flieSize + "K";
        }
        //添加上传文件视图
        var addFileMark = '<div class="upLoadFile" id="' + flieID + '">' +
            ' <div class="fileName">' + fileInfo.files[0].name + '</div>' +
            '  <span>' + flieSize + '</span>' +
            '    <div class="fileProcess">0%</div>' +
            ' <button type="button" class="layui-btn  layui-btn-sm  fileDownload">下载</button>' +
            '      <button type="button" class="layui-btn  layui-btn-sm layui-btn-danger fileRemove">删除</button>' +
            '   </div>';



        // var upLoadFile = document.createElement('div');
        // var fileName = document.createElement('div');
        // var span = document.createElement('span');
        // var fileProcess = document.createElement('div');
        // var fileDownload = document.createElement('button');
        // var fileRemove = document.createElement('button');
        // upLoadFile.className = "upLoadFile";
        // upLoadFile.id = flieID;
        // fileName.className = 'fileName';
        // fileName.innerHTML = fileInfo.files[0].name;
        // span.innerHTML = flieSize;
        // fileProcess.className = "fileProcess";
        // fileProcess.innerHTML = '0%';
        // fileDownload.className = "fileDownload layui-btn layui-btn-sm";
        // fileDownload.innerHTML = "下载";
        // fileRemove.className = "fileRemove layui-btn-sm layui-btn layui-btn-danger";
        // fileRemove.innerHTML = "删除";
        // upLoadFile.appendChild(fileName);
        // upLoadFile.appendChild(span);
        // upLoadFile.appendChild(fileProcess);
        // upLoadFile.appendChild(fileDownload);
        // upLoadFile.appendChild(fileRemove);
        // var fileUploadList = document.getElementById('fileUploadList');
        // console.log(typeof fileUploadList);
        // if (fileUploadList) {
        //     // document.getElementById('fileUploadList').innerHtml = "ssss";
        //     fileUploadList.appendChild(upLoadFile);
        //     console.log(document.getElementById('fileUploadList'));
        // } else {
        //     fileUploadList.appendChild(upLoadFile);

        //     // document.getElementById('fileUploadList').innerHtml = "ssssssssss";
        //     console.log(document.getElementById('fileUploadList'));
        //     // document.getElementById('fileUploadList').innerHtml = fileUploadList + addFileMark;
        // }

        // fileUploadList
        $(".fileUploadList").append(addFileMark);
        //下载事件绑定
        $('.fileDownload').unbind('click').on('click', function() {
            var FileName = $(this).parents().children().eq(0).text();
            var eleLink = document.createElement('a');
            eleLink.download = FileName;
            eleLink.style.display = 'none';
            eleLink.href = "http://www.ytzed.com/Before/img/NewFream/logo.png?response-content-type=application/octet-stream";
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
        });
        $(".fileRemove").on('click', function() {
            var that = $(this);
            layer.confirm('确定要删除吗', {
                btn: ['确定', '取消'] //按钮
            }, function() { //ajax  请求
                that.parent().remove();
                layer.msg('删除成功', {
                    icon: 1
                });
            }, function() {

            });

        });

        uploadFile();
        //设置连续上传同一个文件
         var e = e || window.event;
         setTimeout(function() {
             if (fileSeccess == 100) {
                e.target.value = '';
            }
         }, 0);
    });


    // 上传
    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;
        }
    }

    function uploadFile() {
        // var fileInfo = document.getElementById("selectFile");
        if (fileInfo.files.length < 1) {
            layer.msg('请添加要上传的文件!', {
                icon: 7
            });
        } else {
            var fileObj = document.getElementById("selectFile").files[0]; // js 获取文件对象
            var formFile = new FormData();
            formFile.append("file", fileObj); //加入文件对象
            var data = formFile;
            $.ajax({
                url: "http://up.qiniu.com/",
                data: data,
                type: "Post",
                dataType: "json",
                cache: false, //上传文件无需缓存
                processData: false, //用于对data参数进行序列化处理 这里必须false
                contentType: false, //必须
                xhr: xhrOnProgress(function(e) {
                    //进度百分比
                    var percent = Math.round(e.loaded / e.total * 100);
                    $('#' + flieID).children(".fileProcess").text(percent + "%");
                    fileSeccess = percent;

                }),
                success: function(result) {
                    if (result) {
                        layer.msg('上传成功', {
                            icon: 6
                        });
                    } else {
                        layer.msg('上传失败', {
                            icon: 5
                        });
                    }

                },
            })
        }

    }


 layui格式 

layui.use('upload', function() {
        var upload = layui.upload;
        var fileListView = $('#fileList')
            //执行实例
        var uploadInst = upload.render({
            elem: '#',
            url: 'https://mail.qq.com/cgi-bin/uploadunite?func=CheckFile&inputf=json&outputf=json&sid=t8xG79W2jNB5S0wR',
            method: "post",
            data: {},
            accept: "file",
            auto: false,
            exts: 'jpg|png|jpeg|pdf|ppt|xls|doc|txt|zip|7z|rar|psd|gif|docx|pptx|xlsx',
            choose: function(obj) {
                //将每次选择的文件追加到文件队列
                // var files = obj.pushFile();
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
                obj.preview(function(index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name + '</td>', '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>', '<td>等待上传</td>', '<td>', '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>', '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>', '</td>', '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function() {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function() {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadInst.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                    });

                    fileListView.append(tr);
                });
            },
            done: function(res) {

            },
            error: function() {}
        });
    });

下载为csv文件

 let time = new Date()
        let year = time.getFullYear()
        let month = time.getMonth() + 1
        let day = time.getDate()
        let hours = time.getHours()
        let minutes = time.getMinutes()
        let seconds = time.getSeconds()
        let name =
          year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds
        let elem = sourceData
        let str = ''
        for (let m in tableLabel) {
          str+= tableLabel[m].title+','
        }
        str+='\n'
        for (let i = 0; i < elem.length; i++) {
          for (let item in tableLabel) {
            if (elem[i][tableLabel[item].porp] == '/') {
              str += `${' '+ '\t'},`
            } else {
              str += `${elem[i][tableLabel[item].porp] + '\t'},`
            }
          }
          str += '\n'
        }
        //encodeURIComponent解决中文乱码
        let url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
        let link = document.createElement('a')
        link.href = url
        link.download = name + '数据表.csv'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值