关于自定义一个上传的file按钮

在input中html给我们一个 type  file用来做文件上传的功能,比如

但是这样的样式,实在难看,在开发的时候看了layui和bootstrap的点击上传,都很不错。

前者的调用方式和js的差别太大,后者需要引入bootstrap fileinput.js 我都不是很满意,

后来写了一个原生的js来调用,话说我还是引用了layui的css样式,因为确实不错

 

看下代码

1     <input type="file" onchange="upload()" style="display:none" id="file-input" />
2     <button onclick='selectFile()'>上传</button>

这是没有引入layui的类之前的html,他的input type file是默认隐藏的,我们可以在

按钮上模拟input的点击事件

var inputBox = document.getElementById("file-input");
        
        function selectFile(){
            inputBox.click()
        }        

点击之后,input就相当于被点击,开始上传文件,当上传文件的时候,input上绑定的onchange();就开始生效了

这是一个加载的函数

function upload(){
        //alert(123);
            var file = inputBox.files[0]
            if(! file){
                alert('请选择文件')
                return
            }
            var form = new FormData()
            form.append('file',file)
            var xhr = new XMLHttpRequest();
            xhr.open("post", '../../api/receiveOptionQuestion', true);      
            xhr.onload = function () {   
                alert(xhr.responseText);
            };
            xhr.upload.addEventListener("progress", function(e){
                console.log(e.loaded / e.total * 100)
            }, false);
            xhr.send(form);
        }

在open方法中定义上传的接口,返回数据为responseText 

加载数据的时候,绑定一个进度的事件,可以由e.loaded/e.total*100+"%"得到当前的进度(百分数)

最后传值

posted @ 2018-01-30 22:32  AmbitiousZy  阅读(367)  评论(0编辑  收藏  举报