zoukankan      html  css  js  c++  java
  • 关于自定义一个上传的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+"%"得到当前的进度(百分数)

    最后传值

  • 相关阅读:
    带字数限制提示的输入框效果
    js快速获取数组中的最大值最小值
    js实现连线题
    js自定义图片提示效果
    为了遇见你
    为了明天(励志篇)
    你为什么总是不理我
    爱情,是我一生中最虔诚的信仰
    你是我心中永远抹不掉的痛
    爱你一万次够不够
  • 原文地址:https://www.cnblogs.com/czy960731/p/8387678.html
Copyright © 2011-2022 走看看