input 设置上传文件类型

H5 给 input 增加了属性 accept 属性,可以设置实现,在点击按钮的时候默认过滤你需要上次的文件。当然它不能强制的限制用户选择用户上传的文件类型

Example

  • 上传 Excel 2007版本
<input  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" onclick="oneUploadFile(this)"  type="file" class="updateFile" value="上传文件">
  • 上传 Excel 2007版本及其以上和 2003版本
<input   accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onclick="oneUploadFile(this)"  type="file" class="updateFile" value="上传文件">

如果有多个类型需要在 accept 里继续添加文件类型,并且用逗号隔开。
可以参照这个表格设置上传匹配的类型。

上传文件 Input Accept 设置匹配值
Excel 2003(.xls) application/vnd.ms-excel
Excel 2007 及其以上(.xlsx) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.csv .csv
图片 image/*
文本文件 text/plain
HTML 文件 text/html
video 文件 video/*
audio 文件 audio/*
.wav 文件 .wav
PDF 文件 .pdf

完整的例子

/**
 * 上传文件
 * @param dom    点击上传文件按钮的dom元素
 * @param url    url 地址
 * @param callback 执行之后的回掉函数
 *  @param fileType 文件类型。
 */
function uploadFileTemp(dom, url, fileType, callback) {
    dom.unbind("change");
    dom.bind("change", function() {
            //判断用户是否选择了文件
            if (this.value) {
                var progress = new defaultLoadProgress();
                progress.changeProgress(0);
                uploadTemp({
                    url: url,
                    dom: dom[0],
                    atype: fileType,
                    progress: progress,
                    success: function(res) {
                        if (callback instanceof Function) {
                            callback(res)
                        }
                    }

                })

                this.value = null;
            }
        })
        //防止点击事件冒泡
    return false;
}


/**
 *文件上传对象
 * @param obj  is Object {
 *          url:上传对应的地址,
 *          params:参数
 *          dom:上传的input标签id
 *          type:上传类型,默认是POST
 *          success:成功回掉函数
 *          error: 失败调用函数
 *          progress:显示进度条调用函数
 * } 
 *  
 * @returns {Boolean}
 */
function uploadTemp(obj) {
    var url = obj.url,
        dom = obj.dom,
        type = obj.type || "POST",
        success = obj.success,
        error = obj.error,
        timeout = obj.timeout || 60,
        atype = obj.atype,
        progress = obj.progress;



    var fd = new FormData();
    var file = dom.files[0];

    var loadingInterval = null;
    var loadingNum = 0; //前端自定上传大小
    var loadedNum = 0; //已经上传的文件大小


    if (url.indexOf("?") != -1) {
        url += "&time=" + Math.random();
    } else {
        url += "?time=" + Math.random();
    }

    //验证上传的文件是否符合规范
    if (!judgeFile(file, atype)) {
        progress.onClose();
        return false;
    }

    fd.append("file", file);

    xhr = createXMLHppt();
    var timeout = fileRequestTimeOut(xhr, timeout);
    xhr.open(type, url, true); //更改成false是同步方式请求,true是异步方式请求
    xhr.upload.addEventListener("progress", uploadProgres, false); //显示上传的进度条
    xhr.addEventListener("load", uploadComplete, false); //上传完成
    xhr.addEventListener("error", uploadFiled, false); //上传出现错误
    xhr.addEventListener("abort", uploadCanceled, false); //终止上传
    xhr.addEventListener("loadstart", uploadStart, false); //开始上传
    xhr.addEventListener("timeout", uploadTimeout, false);

    //设置最长等待时间
    xhr.timeout = timeout * 1000;

    //文件上传标注请求头
    //xhr.setRequestHeader("content-type","multipart/form-data");
    xhr.send(fd);
    //在上传的时候返回进度。

    function uploadStart(evt) {
        console.log("start")
        if (progress instanceof Object) {
            loadingInterval = setInterval(function() {
                loadingNum += 2
                if (loadingNum < loadedNum) {
                    progress.changeProgress(loadingNum);
                }
            }, 100)

        }
    }

    function uploadProgres(evt) {
        console.log("progress");
        var num = (evt.loaded / evt.total * 100).toFixed(0);
        loadedNum = num;
        console.log(num);
    }



    function uploadComplete(evt) {
        console.log("complete");
        setTimeout(function() {
            if (success instanceof Function) {
                success(evt.target.responseText);
            };
            clearInterval(loadingInterval);
            //直接设置100%
            progress.changeProgress(100);
            progress != null, progress.onClose();
        }, 500);
        //清除定时器
        clearTimeout(timeout);

    }

    function uploadFiled(evt) {
        console.log("error");
        setTimeout(function() {
            if (error instanceof Function) {
                error(evt)
            } else {
                defaultAlert(evt.message);
            }
            progress != null, progress.onClose();
        }, 300)

        //清除定时器
        clearTimeout(timeout);
        clearInterval(loadingInterval);

    }

    function uploadCanceled(evt) {
        console.log("abort:终止上传");
        setTimeout(function() {
                progress != null, progress.onClose();
                defaultAlert(file.name + "上传失败.")
            }, 300)
            //清除定时器
        clearTimeout(timeout);
        clearInterval(loadingInterval);
        //终止请求
        xhr.abort();
    }

    function uploadTimeout(evt) {
        console.log("上传超时");
        setTimeout(function() {
                progress != null, progress.onClose();
                defaultAlert("上传超时,请再次上传.")
            }, 300)
            //清除定时器
        clearTimeout(timeout);
        clearInterval(loadingInterval);
        //终止请求
        xhr.abort();
    }


    function createXMLHppt() {
        var xmlhttp = "";

        xmlhttp = window.XMLHttpRequest || window.ActiveXObject;

        return new xmlhttp();
    }



    function judgeFile(f, atype) {
        var pass = true;
        //上传word文
        //atype:  ["application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
        //上传excel文件:2007版本以上 ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
        var errorMessage = "";
        switch (atype) {
            case "excel":
                atype = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"];
                errorMessage = "上传文件不是指定的xlsx/xls文件,请重新选择.";
                break;
            case "word":
                //支持所有的word版本
                atype = ["application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
                errorMessage = "上传文件不是指定的docx/doc文件,请重新选择.";
                break;
        }
        var type = f.type; //获取上传文件的类型
        var size = f.size / 1024 / 1024; //获取大小 单位是“M”
        console.log(type)
            //判断大小
        if (size > 50) {
            defaultAlert("选择的文件过大,最大不超过50M.");
            pass = false;

        } else if (size == 0) {
            defaultAlert("请不要上传空白文件.");
            pass = false;

        } else if (atype instanceof Array && atype.indexOf(type) == -1) { //判断文件类型
            defaultAlert("上传的文件不是指定类型“xlsx/xls”,请重新选择.");

            pass = false;

        }


        return pass
    }

    function fileRequestTimeOut(xmlhttp, time) {
        tile = time || 30;
        var timeout = setTimeout(function() {
            xmlhttp.abort();
        }, time * 1000);

        return timeout;
    }
}


// -------------------------------------------------------
// 调用代码,HTML 部分在 input 可以看到。代码里的 defaultAlert 是调用一个弹出消息框。
function oneUploadFile(obj) {
    var url = "rest/upload/excel";
    var dom = $(obj)
    uploadFileTemp(dom, url, "excel", function(res) {
        res = JSON.parse(res);
        if (res.success == true) {
            defaultAlert("上传成功");
        } else {
            defaultAlert(res.error);
        }

    });

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。