手记

简单 js fileUpload控件

file_upload_demo.html

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <script src="../static/dist/js/jquery-1.11.3.min.js"></script>    <script src="../static/js/ys_ui_plugin/simple_file_upload.js"></script></head><body>    <a href="javascript:void(0)">上传文件</a>    <img />    <script>        $("a").simpleUploadFile({            changeCallback:function(file){                var fileReader = new FileReader();                fileReader.onload = function(){                    $("img").attr("src",this.result);                };                fileReader.readAsDataURL(file);            }        });    </script></body></html>

simple_file_upload.js

(function($){    var defaultSettings = {        acceptTypes:["jpg","png"], // 接受的上传文件类型        changeCallback:function(file){        } // 自定义input[type=file] change事件    };    var renderHtml = "<input type='file' style='display:none;'/>";    // 添加隐藏的    function renderInputFile(target,settings){        // 生成dialog唯一标识        var id = "ys_simple_file_upload_"+new Date().getTime()+""+parseInt(Math.random());        $(target).attr("ys_simple_file_upload",id);        $(renderHtml).attr("id",id).appendTo("html"); // 添加到文档中去        return $("#"+id);    }    function bindEventHandlers(container,settings){        var changeCallback = settings.changeCallback;        $(container).change(function(e){            e.preventDefault();            e.stopPropagation();            var file = e.target.files[0];            if(!validateFileType(file,settings)){                alert("文件类型不正确!");                return;            }            changeCallback(file);        });    }    // 验证文件类型    function validateFileType(file,settings){        var acceptTypes = settings.acceptTypes;        var name = file.name;        var fileSuffix = name.substr(name.lastIndexOf(".")+1);        for(var i=0;i<acceptTypes.length;i++){            var acceptType = acceptTypes[i];            if(acceptType==fileSuffix){                return true;            }        }        return false;    }    var options = {        simpleUploadFile:function(settings) {            var mergedSettings = {};            $.extend(mergedSettings,defaultSettings,settings);            var container = renderInputFile(this,mergedSettings);            bindEventHandlers(container,mergedSettings);            $(this).click(function(e){                e.preventDefault();                e.stopPropagation();                $(container).click();            });        }    };    $.fn.extend(options);})(jQuery);

0人推荐
随时随地看视频
慕课网APP