100门课程在线学

基本用法

把下面的代码加入你的HTML页面的body中,确保已经加载了插件库(详见用法部分

  1. 使用file类自动初始化一个文件输入部件。
     <label class="control-label"> 选择文件 </label>
     <input type="file" class="file">
    
  2. 隐藏预览缩略图
     <label class="control-label"> 选择文件 </label>
     <input type="file" class="file" data-show-preview="false">
    
  3. 使用输入标签的input属性(如多文件上传设置multiple)来设置输入行为,并通过data-*属性来设置插件参数。

    样例1

     <label class="control-label"> 选择文件 </label>
     <input name="input[]" type="file" class="file" multiple data-show-upload="false" data-show-caption="true">
     <!-- 多文件上传,不显示上传按钮,显示标题 -->
    

    样例2

     <label class="control-label">Select File</label>
     <input name="input[]" multiple type="file" class="file file-loading" data-allowed-file-extensions='["csv", "txt"]'>
     <!-- `file-loading`类的作用是在插件DOM元素加载时显示一个旋转指示器 -->
     <!-- 允许输入文件的后缀有`csv`和`txt`,使用HTML标记语言传递JSON参数 -->
    
  4. 设置文件输入部件为只读或者禁用状态。
     <label class="control-label"> 只读输入框 </label>
     <input type="file" class="file" readonly="true">
     <label class="control-label"> 禁用输入框 </label>
     <input type="file" class="file" disabled="true">
    
  5. 通过JavaScript初始化输入框部件

    样例1

     <label class="control-label"> 选择文件 </label>
     <input id="input" name="input[]" type="file" multiple class="file-loading">
     <!-- `file-loading`类作用是在插件DOM元素加载时显示一个旋转指示器 -->
    
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({showCaption: false}); //输入框部件只显示选择文件按钮,隐藏标题
         });
     </script>
    

    样例2

     <label class="control-label"> 选择文件 </label>
     <input id="input" name="input[]" type="file" multiple class="file-loading">
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({
                 showUpload: false,            //隐藏上传按钮
                 maxFileCount: 10,             //输入文件数量最大为10
                 mainClass: "input-group-lg"   //文件输入框为大型号
             });
         });
     </script>
    

    高级用法

  6. 初始预览
     <label class="control-label"> 行星和卫星 </label>
     <input id="input" name="input[]" type="file" multiple class="file-loading">
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({
                 initialPreview: [
                     'http://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/631px-FullMoon2010.jpg',
                     'http://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Earth_Eastern_Hemisphere.jpg/600px-Earth_Eastern_Hemisphere.jpg'
                 ],
                 initialPreviewAsData: true,
                 initialPreviewConfig: [
                     {caption: "Moon.jpg", size: 930321, width: "120px", key: 1},
                     {caption: "Earth.jpg", size: 1218822, width: "120px", key: 2}
                 ],
                 deleteUrl: "/site/file-delete",    //删除操作的URL地址
                 overwriteInitial: false,           //不允许覆盖初始的预览,所以添加文件时不会覆盖
                 maxFileSize: 100,                  //文件最大不超过100KB
                 initialCaption: "月球和地球"
             });
         });
     </script>
    
  7. 精简部件

     <label class="control-label"> 选择文件 </label>
     <input id="input" type="file" class="file-loading">
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({
                 browseClass: "btn btn-primary btn-block",
                 showCaption: false,    //不显示标题
                 showRemove: false,     //不显示删除按钮
                 showUpload: false      //不显示上传按钮
             });    //只显示选择文件的按钮
         });
     </script>
    
  8. 自定义部件按钮

     <label class="control-label">Select File</label>
     <input id="input-21" type="file" accept="image/*" class="file-loading">
     <!-- 只接受图像文件 -->
    
     <script>
         $(document).on('ready', function() {
             $("#input-21").fileinput({
                 previewFileType: "image",
                 browseClass: "btn btn-success",
                 browseLabel: "Pick Image",
                 browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
                 removeClass: "btn btn-danger",
                 removeLabel: "Delete",
                 removeIcon: "<i class=\"glyphicon glyphicon-trash\"></i> ",
                 uploadClass: "btn btn-info",
                 uploadLabel: "Upload",
                 uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> "
             });
         });
     </script>
    
  9. 自定义预览背景
     <label class="control-label">Select File</label>
     <input id="input" name="input[]" type="file" class="file-loading" accept="text/plain" multiple>
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({
                 previewFileType: "text",   //预览文件类型
                 allowedFileExtensions: ["txt", "md", "ini", "text"],  //允许的文件后缀
                 previewClass: "bg-warning"    //预览样式CSS类
             });
         });
     </script>
    
  10. 自定义部件模板
     <label class="control-label">Select File</label>
     <input id="input-23" name="input23[]" type="file" multiple class="file-loading">
     <script>
         $(document).on('ready', function() {
             $("#input-23").fileinput({
                 showUpload: false,
                 layoutTemplates: {
                     main1: "{preview}\n" +
                     "<div class=\'input-group {class}\'>\n" +
                     "   <div class=\'input-group-btn\'>\n" +
                     "       {browse}\n" +
                     "       {upload}\n" +
                     "       {remove}\n" +
                     "   </div>\n" +
                     "   {caption}\n" +
                     "</div>"
                 }    //把默认的模板反向排列按钮
             });
         });
     </script>
    
  11. 动态修改输入框
     <label class="control-label">Select File</label>
     <input id="input" name="input40[]" type="file" class="file" multiple>
     <br>
     <button type="button" class="btn btn-warning btn-modify">Modify</button>
     <script>
         //当点击`Modify`按钮时,切换文件输入的禁用状态并改变它的参数
         $(document).on('ready', function() {
             $(".btn-modify").on("click", function() {
                 var $btn = $(this);
                 if ($btn.text() == "Modify") {
                     $("#input").fileinput("disable").fileinput("refresh", {showUpload: false});
                     $btn.html("Revert");
                     alert("Hurray! I have disabled the input and hidden the upload button.");
                 }
                 else {
                     $("#input").fileinput("enable").fileinput("refresh", {showUpload: true});
                     $btn.html("Modify");
                     alert("Hurray! I have reverted back the input to enabled with the upload button.");
                 }
             });
         });
     </script>
    
  12. 控制上传文件
     <label class="control-label">Select File</label>
     <input id="input" name="input[]" type="file" multiple class="file-loading">
     <script>
         //上传文件类型为图像或者视频,最大上传数量为10
         $(document).on('ready', function() {
             $("#input").fileinput({
                 maxFileCount: 10,
                 allowedFileTypes: ["image", "video"]
             });
         });
     </script>
    

     <label class="control-label">Select File</label>
     <input id="input" name="input[]" type="file" multiple class="file-loading">
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({
                 maxFileCount: 10,
                 allowedFileExtensions: ["jpg", "gif", "png", "txt"]
             });
         });
     </script>
    
  13. 自定义错误信息容器

     <label class="control-label">Select File</label>
     <input id="input" name="input[]" type="file" multiple class="file-loading">
     <div id="errorBlock" class="help-block"></div>
     <script>
         $(document).on('ready', function() {
             $("#input").fileinput({
                 showPreview: false,
                 allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
                 elErrorContainer: "#errorBlock"
             });
         });
     </script>
    
  14. 文件大小控制
     <label class="control-label">Select File</label>
     <input id="input-44" name="input44[]" type="file" multiple class="file-loading">
     <div id="errorBlock" class="help-block"></div>
     <script>
         $(document).on('ready', function() {
             $("#input-44").fileinput({
                 uploadUrl: '/file-upload-batch/2',    //未设置此属性,输入框为一条形控件;设置后,出现文件拖拽区域。
                 maxFilePreviewSize: 10240        //最大文件大小10240KB(10M),如果不设置,默认大小25M
             });
         });
     </script>
    

    文件夹上传

    使用webkitdirectory属性在文件夹中递归上传文件。此功能仅由少数现代浏览器(如Chrome和IE Edge)支持。要使用此功能,必须使用文件选择器按钮(即浏览按钮)来选择文件夹。注意:无法通过拖放功能使用此功能。

上传头像

一个展示如何使用插件管理用户个人资料图片上传(或头像)的示例。这是通过简单的基于表单的上传方案实现的。该示例展示了如何使用defaultPreviewContent设置默认的用户配置图片文件(或先前保存的图片)。接下来,你可以通过将showCaption设置为false来显示快速头像上传小部件。main1布局因此被禁用,并且使用main2布局。将showClose设置为false可以隐藏预览的关闭按钮。然后,你可以调整其他标签和CSS类属性。你还可以将自己的自定义按钮添加到用于管理图片的layoutTemplates.main2模板中。可以设置自定义错误容器标识符以显示文件验证错误。

多语言

fileinput插件支持在同一页面上显示多个语言的窗口小部件。想这样做,请按照以下简单步骤操作:

  • 加载所需的语言JS文件(例如俄语,加载js/locales/ru.js)。这些必须在fileinput.js之后加载。
  • 将插件中的语言属性设置为你需要的语言(例如langage:'ru')。

主题

Krajee浏览器主题

预览管理

使用版本v4.3.2,文件输入插件包括高级预览布局管理,轻松设置初始预览只需数据而不是完整的标记语言,初始预览排序和重新排列,以幻灯片格式缩放内容(具有无边界/全屏幕支持)。

初始预览数据

多种方法来管理你的预览。此示例中显示了以下功能:

  • initialPreviewAsData属性设置为true。这样做你就可以在initialPreview属性中传入纯数据,而不需要完整的标记语言(插件的v4.3.2版本的一个特性)。数据会根据预览文件类型自动解析并使用previewTemplates规定的模板标记渲染。
  • 从v4.3.2版本开始,增添了initialPreviewConfig属性。你可以配置文件类型来自动提取展示每个文件预览的模板。如果没有设置它,就会使用默认的initialPreviewFileType属性(默认值为image)。
  • 能够缩放并检查各种类型文件的详细预览/幻灯片。下面的示例演示了图像,视频,pdf,文本和html类型。
  • 多种缩放预览功能。点击预览内容中的无边框最大化屏幕、全屏预览和隐藏标题功能按钮。使用指示灯或键盘左/右按钮自动在预览缩略图之间导航。还要注意,新选择的文件(通过浏览/拖放)也可以与初始预览相接演示。
  • 能够重新排序和排序/重新排列初始预览内容。选中左下方的拖动指示器拖动缩略图并重新排列。
  • 通过filesorted事件在初始预览中捕获修改后的文件堆栈(插件将这些内容作为本示例的控制台日志输出)。你还可以通过读取插件的initialPreviewConfig属性来获取最新的排序数据。

      <!-- 预览数据 -->
      <!-- 按照正确得顺序加载JS文件 -->
      <!-- 排序插件,排序/重排列初始预览文件 -->
      <script src="/path/to/js/plugins/sortable.min.js"></script>
      <!-- 净化插件,使预览HTML内容安全渲染 -->
      <script src="/path/to/js/plugins/purify.min.js"></script>
      <script src="/path/to/js/fileinput.js"></script>
    
      <label class="control-label">选择文件</label>
      <input id="input" name="input[]" type="file" multiple class="file-loading">
      <script>
          $("#input").fileinput({
              uploadUrl: "/file-upload-batch/1",
              uploadAsync: false,
              minFileCount: 2,
              maxFileCount: 5,
              overwriteInitial: false,
              initialPreview: [
                  // 图像数据
                  "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Desert.jpg",
                  // 图像数据
                  "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Lighthouse.jpg",
                  // 视频数据
                  "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/small.mp4",
                  // PDF数据
                  'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/pdf-sample.pdf',
                  // 文本数据
                  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut mauris ut libero fermentum feugiat eu et dui. Mauris condimentum rhoncus enim, sed semper neque vestibulum id. Nulla semper, turpis ut consequat imperdiet, enim turpis aliquet orci, eget venenatis elit sapien non ante. Aliquam neque ipsum, rhoncus id ipsum et, volutpat tincidunt augue. Maecenas dolor libero, gravida nec est at, commodo tempor massa. Sed id feugiat massa. Pellentesque at est eu ante aliquam viverra ac sed est.",
                  // HTML数据
                  '<div class="text-center">' + 
                  '<h3>Lorem Ipsum</h3>' + 
                  '<p><em>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</em></p>' + 
                  '<h5><small>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</small></h5>' + 
                  '<hr>' + 
                  '</div>' + 
                  '<div class="text-justify">' + 
                  '<p>' + 
                  'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed convallis convallis dolor sed dignissim. Phasellus euismod mauris vel dolor maximus, sed fermentum mauris lobortis. Aliquam luctus, diam in luctus egestas, magna lacus luctus libero, scelerisque mattis ante dolor ac nunc. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse varius orci ultricies massa euismod, at semper turpis fermentum. Quisque vitae augue vel lectus viverra facilisis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla lacinia molestie diam, et volutpat nunc bibendum a. Cras a est sed augue commodo accumsan quis vitae nisi.' + 
                  '</p>' + 
                  '<p>' + 
                  'Nunc sit amet metus et dui aliquet feugiat. Praesent lobortis, ipsum et elementum dignissim, urna libero fringilla justo, at tincidunt nisi mi sed mi. Integer vel est porttitor, tempor tortor non, lobortis felis. Curabitur porttitor nisi et volutpat iaculis. Fusce nec feugiat lectus, vitae ullamcorper lorem. Ut ultrices nunc imperdiet placerat malesuada. Proin commodo erat in egestas maximus.' + 
                  '</p>'
              ],
              initialPreviewAsData: true, // 确定你是否仅发送预览数据,而不是原始标记
              initialPreviewFileType: 'image', // `image`是默认值,可以在下面的配置中覆盖
              initialPreviewConfig: [
                  {caption: "Desert.jpg", size: 827000, width: "120px", url: "/file-upload-batch/2", key: 1},
                  {caption: "Lighthouse.jpg", size: 549000, width: "120px", url: "/file-upload-batch/2", key: 2}, 
                  {type: "video", size: 375000, filetype: "video/mp4", caption: "KrajeeSample.mp4", url: "/file-upload-batch/2", key: 3}, 
                  {type: "pdf", size: 8000, caption: "About.pdf", url: "/file-upload-batch/2", key: 4},
                  {type: "text", size: 1430, caption: "LoremIpsum.txt", url: "/file-upload-batch/2", key: 5}, 
                  {type: "html", size: 3550, caption: "LoremIpsum.html", url: "/file-upload-batch/2", key: 6}
              ],
              purifyHtml: true, // 这是默认情况下为预览净化HTML数据
              uploadExtraData: {
                  img_key: "1000",
                  img_keywords: "happy, places",
              }
          }).on('filesorted', function(e, params) {
              console.log('File sorted params', params);
          }).on('fileuploaded', function(e, params) {
              console.log('File uploaded params', params);
          });
      </script>
    

原生初始预览

在上面的演示场景中,你可以在initialPreview中设置原始标记语言而不是数据。

    <style>
    .krajee-init-preview {
        height:160px
    }
    </style> 
    <label class="control-label">Select File</label>
    <input id="input-pr" name="input-pr[]" type="file" multiple class="file-loading">
    <script>
        $("#input-pr").fileinput({
            uploadUrl: "/file-upload-batch/1",
            uploadAsync: false,
            minFileCount: 2,
            maxFileCount: 5,
            overwriteInitial: false,
            initialPreview: [
                // 图像原生标记语言
                '<img src="http://lorempixel.com/800/460/nature/1" class="kv-preview-data krajee-init-preview file-preview-image">',
                // 图像原生标记语言
                '<img src="http://lorempixel.com/800/460/nature/2" class="kv-preview-data krajee-init-preview file-preview-image">',
                // 文本原生标记语言
                '<textarea class="kv-preview-data file-preview-text" readonly style="width:213px;height:160px">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut mauris ut libero fermentum feugiat eu et dui. Mauris condimentum rhoncus enim, sed semper neque vestibulum id. Nulla semper, turpis ut consequat imperdiet, enim turpis aliquet orci, eget venenatis elit sapien non ante. Aliquam neque ipsum, rhoncus id ipsum et, volutpat tincidunt augue. Maecenas dolor libero, gravida nec est at, commodo tempor massa. Sed id feugiat massa. Pellentesque at est eu ante aliquam viverra ac sed est.</textarea>'
            ],
            initialPreviewAsData: false, // 运行你设置原生标记语言
            initialPreviewFileType: 'image', // 默认值为`image`,可以在下面配置中被覆盖
            initialPreviewConfig: [
                {type: "image", caption: "Nature-1.jpg", size: 847000, url: "/site/file-delete", key: 11},
                {type: "image", caption: "Nature-2.jpg", size: 817000, url: "/site/file-delete", key: 12},  // set as raw markup
                {type: "text", size: 1430, caption: "LoremIpsum.txt", url: "/site/file-delete", key: 13}
            ],
            uploadExtraData: {
                img_key: "1000",
                img_keywords: "happy, nature",
            }
        }).on('filesorted', function(e, params) {
            console.log('File sorted params', params);
        }).on('fileuploaded', function(e, params) {
            console.log('File uploaded params', params);
        });
    </script>

高级初始预览

initialPreviewConfig中配置高级属性。通过为每个文件配置设置previewAsData布尔属性来合并数据和原始标记。另外在配置级别设置type以识别预览模板,设置文件类型以识别特定模板(如视频)。

    <label class="control-label">Select File</label>
    <input id="input-pa" name="input-pa[]" type="file" multiple class="file-loading">
    <script>
        $("#input-pa").fileinput({
            uploadUrl: "/file-upload-batch/1",
            uploadAsync: false,
            minFileCount: 2,
            maxFileCount: 5,
            overwriteInitial: false,
            initialPreview: [
                // 图像数据
               'http://lorempixel.com/800/460/business/1',
                // 图像原生标记语言
                '<img src="http://lorempixel.com/800/460/business/2" class="kv-preview-data file-preview-image" style="height:160px">',
                // PDF数据
                'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/pdf-sample.pdf',
                // 视频数据
                "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/small.mp4",
            ],
            initialPreviewAsData: true, // 默认为数据
            initialPreviewFileType: 'image', // 默认为`image`,可在配置中覆盖
            initialPreviewConfig: [
                {caption: "Business-1.jpg", size: 762980, url: "/site/file-delete", key: 8},
                {previewAsData: false, size: 823782, caption: "Business-2.jpg", url: "/site/file-delete", key: 9}, 
                {type: "pdf", size: 8000, caption: "PDF-Sample.pdf", url: "/file-upload-batch/2", key: 10}, 
                {type: "video", size: 375000, filetype: "video/mp4", caption: "KrajeeSample.mp4", url: "/file-upload-batch/2", key: 14},  
            ],
            uploadExtraData: {
                img_key: "1000",
                img_keywords: "happy, nature",
            }
        }).on('filesorted', function(e, params) {
            console.log('File sorted params', params);
        }).on('fileuploaded', function(e, params) {
            console.log('File uploaded params', params);
        });
    </script>

初始预览图例

和上面的例子不同,在初始化预览中缩略图为图例,但在详细预览中为文件内容。此方案结合了初始预览数据的图例预览。还要检查,如何传递和设置initialPreviewConfig中每个文件的captionfilenamefilename在解析文件的扩展名及其模板中非常有用,在这种情况下用于渲染图例预览。caption将显示在每个缩略图下面,默认情况下将被使用为filename,以防文件名未配置。举个例子,使用其他图例预览参考图例预览演示5图例预览演示6

    <label class="control-label">Select File</label>
    <input id="input-iconic" name="input-iconic[]" type="file" multiple class="file-loading">
    <script>
        $("#input-iconic").fileinput({
            uploadUrl: "/file-upload-batch/1",
            uploadAsync: false,
            minFileCount: 2,
            maxFileCount: 5,
            overwriteInitial: false,
            initialPreview: [
                // 图像数据
               'http://lorempixel.com/800/460/business/1',
                // 图像原生标记语言
                '<img src="http://lorempixel.com/800/460/business/2" class="kv-preview-data file-preview-image" style="height:160px">',
                // 文本数据
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut mauris ut libero fermentum feugiat eu et dui. Mauris condimentum rhoncus enim, sed semper neque vestibulum id. Nulla semper, turpis ut consequat imperdiet, enim turpis aliquet orci, eget venenatis elit sapien non ante. Aliquam neque ipsum, rhoncus id ipsum et, volutpat tincidunt augue. Maecenas dolor libero, gravida nec est at, commodo tempor massa. Sed id feugiat massa. Pellentesque at est eu ante aliquam viverra ac sed est.",
                // PDF数据
                'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/pdf-sample.pdf',
                // 视频数据
                "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/small.mp4",
            ],
            initialPreviewAsData: true, // 默认为数据
            initialPreviewFileType: 'image', // 默认为`image`,在下面的配置中可以覆盖
            initialPreviewConfig: [
                {caption: "Business 1", filename: "Business-1.jpg", size: 762980, url: "/site/file-delete", key: 11},
                {previewAsData: false, size: 823782, caption: "Business 2", filename: "Business-2.jpg", url: "/site/file-delete", key: 13}, 
                {caption: "Lorem Ipsum", filename: "LoremIpsum.txt", type: "text", size: 1430, url: "/site/file-delete", key: 12}, 
                {type: "pdf", size: 8000, caption: "PDF Sample", filename: "PDF-Sample.pdf", url: "/file-upload-batch/2", key: 14}, 
                {type: "video", size: 375000, filetype: "video/mp4", caption: "Krajee Sample", filename: "KrajeeSample.mp4", url: "/file-upload-batch/2", key: 15},  
            ],
            uploadExtraData: {
                img_key: "1000",
                img_keywords: "happy, nature",
            },
            preferIconicPreview: true, // 这将强制缩略图按照以下文件扩展名的图标显示
            previewFileIconSettings: { // 配置你的文件扩展名对应的图标
                'doc': '<i class="fa fa-file-word-o text-primary"></i>',
                'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                'ppt': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
                'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
                'htm': '<i class="fa fa-file-code-o text-info"></i>',
                'txt': '<i class="fa fa-file-text-o text-info"></i>',
                'mov': '<i class="fa fa-file-movie-o text-warning"></i>',
                'mp3': '<i class="fa fa-file-audio-o text-warning"></i>',
                // 以下这些文件类型的注释未配置扩展名确定逻辑(键值本身会被用作扩展名)
                // has been configured (the keys itself will be used as extensions)
                'jpg': '<i class="fa fa-file-photo-o text-danger"></i>', 
                'gif': '<i class="fa fa-file-photo-o text-muted"></i>', 
                'png': '<i class="fa fa-file-photo-o text-primary"></i>'    
            },
            previewFileExtSettings: { // 配置确定图标文件扩展名的逻辑代码
                'doc': function(ext) {
                    return ext.match(/(doc|docx)$/i);
                },
                'xls': function(ext) {
                    return ext.match(/(xls|xlsx)$/i);
                },
                'ppt': function(ext) {
                    return ext.match(/(ppt|pptx)$/i);
                },
                'zip': function(ext) {
                    return ext.match(/(zip|rar|tar|gzip|gz|7z)$/i);
                },
                'htm': function(ext) {
                    return ext.match(/(htm|html)$/i);
                },
                'txt': function(ext) {
                    return ext.match(/(txt|ini|csv|java|php|js|css)$/i);
                },
                'mov': function(ext) {
                    return ext.match(/(avi|mpg|mkv|mov|mp4|3gp|webm|wmv)$/i);
                },
                'mp3': function(ext) {
                    return ext.match(/(mp3|wav)$/i);
                },
            }
        }).on('filesorted', function(e, params) {
            console.log('File sorted params', params);
        }).on('fileuploaded', function(e, params) {
            console.log('File uploaded params', params);
        });
    </script>

文件预览图标

你可能希望根据每个预览缩略图的文件类型显示自定义文件图标,而不是嵌入文件内容或使用默认的previewFileIcon图标。该插件可以让你设置不同的用户友好型文件类型图标,以便在文件缩略图中显示,而不是默认的previewFileIcon图标。该方法还具有提高性能的优点,因为在该方法中,插件不会调用FileAPI读取和显示文件内容进行预览,减少了内存开销。当你要显示每个文件类型的图标而不是在文件内容时,这也很有用。你必须设置previewFileIconSettings,在其中设置每个文件扩展名的文件类型图标。注意:为了使其有效,你必须配置allowedPreviewTypes 和/或allowedPreviewMimeTypes参数。这些将允许您仅对这些选定的文件类型进行嵌入式内容的解析,并显示其余的文件类型图标。你还可以配置previewFileExtSettings,在高级场景中通过回调自动导出扩展名。

图像尺寸

图像管理

自动替换文件

文件计数验证

插件方法

阿贾克斯上传

具有拖拽功能,基于AJAX 异步/同步的上传。只需要设置uploadurl数据属性,把multiple属性设置为true。请注意,多个上传的文件输入name属性应设置为数组格式。你可以修改上传之前选择的文件,例如增加或删除。对于下面的示例,你可以在服务器上读取上传的name属性为kartik-input-700文件。

  1. 例1
    <input id="input-700" name="kartik-input-700[]" type="file" multiple class="file-loading">
    <script>
        $("#input-700").fileinput({
            uploadUrl: "http://localhost/file-upload-single/1", // 服务器端上传处理程序
            uploadAsync: true,  //异步上传
            maxFileCount: 5     //最大上传文件数为5
        });
    </script>
  1. 例2
    <input id="input-701" name="kartik-input-701[]" type="file" multiple=true class="file-loading">
    <script>
        $("#input-701").fileinput({
            uploadUrl: "http://localhost/file-upload-batch/1", // 服务器端上传处理程序
            uploadAsync: true,
            maxFileCount: 5
        });
</script>
  1. 例3
     <input id="input-702" name="kartik-input-702[]" type="file" multiple=true class="file-loading">
     <script>
         $("#input-702").fileinput({
             uploadUrl: "http://localhost/file-upload-single/1", // 服务器端上传处理程序
             uploadAsync: true,  //异步上传
             minFileCount: 1,    //最小上传文件数: 1
             maxFileCount: 5,    //最大上传文件数: 5
             overwriteInitial: false,  //不能重载初始预览
             initialPreview: [         //初始预览数据
                 "http://lorempixel.com/800/460/people/1",
                 "http://lorempixel.com/800/460/people/2"
             ],
             initialPreviewAsData: true,      // 确定传入预览数据,而不是原生标记语言
             initialPreviewFileType: 'image', // 默认为`image`,可以在下面配置中被覆盖
             initialPreviewConfig: [          //初始预览配置
                 {caption: "People-1.jpg", size: 576237, width: "120px", url: "/site/file-delete", key: 1},
                 {caption: "People-2.jpg", size: 932882, width: "120px", url: "/site/file-delete", key: 2}, 
             ],
             uploadExtraData: {    //上传额外数据
                 img_key: "1000",
                 img_keywords: "happy, places",
             }
         });
     </script>
    
  2. 例4
     <input id="input-703" name="kartik-input-703[]" type="file" multiple class="file-loading">
     <script>
         $("#input-703").fileinput({
             uploadUrl: "http://localhost/file-upload-single/2",
             uploadAsync: true,   //异步上传
             minFileCount: 1,
             maxFileCount: 5,
             uploadExtraData: function(previewId, index) {
                 return {key: index};
             },
             overwriteInitial: false,
             initialPreviewAsData: true // 确定你是仅发送预览数据,而不是标记
         });
     </script>
    
     <?php
     // ...
     // 处理ajax上传并返回JSON响应的服务器代码。
     // 你的服务器方法必须返回一个包含`initialPreview`、`initialPreviewConfig`和`append`的JSON对象。
     // 一个PHP服务器代码示例如下:
     // ...
     $key = '<解析图像关键字的代码>';
     $url = '<你删除这个文件的服务器方法URL>';
     echo json_encode([
         'initialPreview' => [
             "http://path.to.uploaded.file/{$key}.jpg"
         ],
         'initialPreviewConfig' => [
             ['caption' => "Sports-{$key}.jpg", 'size' => 627392, 'width' => '120px', 'url' => $url, 'key' => $key],
         ],
         'append' => true // 是否把这些配置加入`initialPreview`。
                          // 如果设置为`false`,它会重载初始预览。
                          // 如果设置为`true`,它会加入初始预览之中。
                          // 如果这个属性没有被设置或者没有传出,它会默认为`true`。
     ]);
     ?>
    
  3. 例5
     <input id="input-704" name="kartik-input-704[]" type="file" multiple=true class="file-loading">
     <script>
         $("#input-704").fileinput({
             uploadUrl: "http://localhost/file-upload-batch/2", // 服务器上传接收方法
             uploadAsync: false,    //同步上传
             minFileCount: 1,
             maxFileCount: 5,
             initialPreviewAsData: true 
         });
     </script>
    
     <?php
     // ...
     // 处理ajax上传并返回JSON响应的服务器代码。
     // 你的服务器方法必须返回一个包含`initialPreview`、`initialPreviewConfig`和`append`的JSON对象。
     // 一个PHP服务器代码示例如下:
     // ...
     $p1 = $p2 = [];
     if (empty($_FILES['kartik-input-704']['name'])) {
         echo '{}';
         return;
     }
     for ($i = 0; $i < count($_FILES['kartik-input-704']['name']); $i++) {
         $j = $i + 1;
         $key = '<获取图像关键字的代码>';
         $url = '<你的服务器上删除这个图像的服务地址>';
         $p1[$i] = "http://path.to.uploaded.file/{$key}.jpg"; // 发送的数据
         $p2[$i] = ['caption' => "Animal-{$j}.jpg", 'size' => 732762, 'width' => '120px', 'url' => $url, 'key' => $key];
     }
     echo json_encode([
         'initialPreview' => $p1, 
         'initialPreviewConfig' => $p2,   
         'append' => true // 是否把这些配置加入`initialPreview`。
                          // 如果设置为`false`,它会重载初始预览。
                          // 如果设置为`true`,它会加入初始预览之中。
                          // 如果这个属性没有被设置或者没有传出,它会默认为`true`。
     ]);
     ?>
    
  4. 例6
     <input id="input-705" name="kartik-input-705[]" type="file" multiple class="file-loading">
     <script>
         var $input = $("#input-705");
         $input.fileinput({
             uploadUrl: "http://localhost/file-upload-batch/2", // 服务器接收上传文件的方法
             uploadAsync: false,
             showUpload: false, // 隐藏上传按钮
             showRemove: false, // 隐藏移除按钮
             minFileCount: 1,
             maxFileCount: 5
         }).on("filebatchselected", function(event, files) {
             // 选择文件后立即触发上传方法
             $input.fileinput("upload");
         });
     </script>
    
  5. 例7

     <input id="input-706" name="kartik-input-706[]" type="file" multiple=true class="file-loading">
     <style>
         .krajee-default .file-thumb-progress {
             top: 55px
         }
     </style> <!-- 样式重载 -->
     <script>
         var $el2 = $("#input-706");
    
         // 这个场景的自定义页脚模板
         // 自定义标签在大括号里
    
         var footerTemplate = '<div class="file-thumbnail-footer" style ="height:94px">\n' +
         '   <div style="margin:5px 0">\n' +
         '       <input class="kv-input kv-new form-control input-sm text-center {TAG_CSS_NEW}" value="{caption}"         placeholder="Enter caption...">\n' +
         '       <input class="kv-input kv-init form-control input-sm text-center {TAG_CSS_INIT}" value="{TAG_VALUE}" placeholder="Enter caption...">\n' +
         '   </div>\n' +
         '   {size} {progress} {actions}\n' +
         '</div>';
    
         $el2.fileinput({
             uploadUrl: '/file-upload-batch/2',
             uploadAsync: false,
             maxFileCount: 5,
             overwriteInitial: false,
             layoutTemplates: {footer: footerTemplate, size: '<samp><small>({sizeText})</small></samp>'},
             previewThumbTags: {
                 '{TAG_VALUE}': '',        // 无值
                 '{TAG_CSS_NEW}': '',      // 新的缩略图输入
                 '{TAG_CSS_INIT}': 'hide'  // 隐藏初始输入
             },
             initialPreview: [
                 "<img style='height:160px' src='http://lorempixel.com/800/460/city/1'>",
                 "<img style='height:160px' src='http://lorempixel.com/800/460/city/2'>",
             ],
             initialPreviewConfig: [
                 {caption: "City-1.jpg", size: 327892, width: "120px", url: "/site/file-delete", key: 1},
                 {caption: "City-2.jpg", size: 438828, width: "120px", url: "/site/file-delete", key: 2}, 
             ],
             initialPreviewThumbTags: [
                 {'{TAG_VALUE}': 'City-1.jpg', '{TAG_CSS_NEW}': 'hide', '{TAG_CSS_INIT}': ''},
                 {
                     '{TAG_VALUE}': function() { // 回调示例
                         return 'City-2.jpg';
                     },
                     '{TAG_CSS_NEW}': 'hide',
                     '{TAG_CSS_INIT}': ''
                 }
             ],
             uploadExtraData: function() {  // 回调示例
                 var out = {}, key, i = 0;
                 $('.kv-input:visible').each(function() {
                     $el = $(this);
                     key = $el.hasClass('kv-new') ? 'new_' + i : 'init_' + i;
                     out[key] = $el.val();
                     i++;
                 });
                 return out;
             }
         });
     </script>
    
  6. 例8

     <input id="input-707" name="kartik-input-707[]" type="file" multiple=true class="file-loading">
     <script>
     $("#input-707").fileinput({
         uploadUrl: "/file-upload-batch/1",
         uploadAsync: false,
         minFileCount: 2,
         maxFileCount: 5,
         overwriteInitial: false,
         initialPreview: [
             "<img style='height:160px' src='http://lorempixel.com/800/460/nature/1'>",
             "<img style='height:160px' src='http://lorempixel.com/800/460/nature/2'>",
             "<img style='height:160px' src='http://lorempixel.com/800/460/nature/3'>",
         ],
         initialPreviewConfig: [
             {caption: "Food-1.jpg", size: 329892, width: "120px", url: "/site/file-delete", key: 1},
             {caption: "Food-2.jpg", size: 872378, width: "120px", url: "/site/file-delete", key: 2}, 
             {caption: "Food-3.jpg", size: 632762, width: "120px", url: "/site/file-delete", key: 3}, 
         ],
         uploadExtraData: {
             img_key: "1000",
             img_keywords: "happy, nature",
         }
     });
     $("#input-707").on("filepredelete", function(jqXHR) {
         var abort = true;
         if (confirm("Are you sure you want to delete this image?")) {
             abort = false;
         }
         return abort; // 你也可以发送任何数据/对象,只要你可以在`filecustomerror`事件接收。
     });
     <script>
    
  7. 例9
     <input id="input-708" name="kartik-input-708[]" type="file" multiple=true class="file-loading">
     <script>
         $("#input-708").fileinput({
             uploadUrl: "http://localhost/file-upload-batch/1", // 服务器接收上传文件方法
             uploadAsync: false,
             maxFileCount: 5
         }).on('filebatchpreupload', function(event, data) {
             var n = data.files.length, files = n > 1 ? n + ' files' : 'one file';
             if (!window.confirm("你确定要上传 " + files + "?")) {
                 return {
                     message: "上传中断!", // 上传异常信息
                     data:{} // 要发送的任何其他数据,可以在`filecustomerror`中引用
                 };
             }
         });
     </script>
    
  8. 例10
    <input id="input-709" name="kartik-input-709[]" type="file" multiple class="file-loading">
    <div id="kv-error-1" style="margin-top:10px;display:none"></div>
    <div id="kv-success-1" class="alert alert-success fade in" style="margin-top:10px;display:none"></div>
    <script>
        $("#input-709").fileinput({
            uploadUrl: "http://localhost/file-upload-single/1", // 服务器接收上传文件方法
            uploadAsync: true,
            showPreview: false,
            allowedFileExtensions: ['jpg', 'png', 'gif'],
            maxFileCount: 5,
            elErrorContainer: '#kv-error-1'
        }).on('filebatchpreupload', function(event, data, id, index) {
            $('#kv-success-1').html('<h4>上传状态</h4><ul></ul>').hide();
        }).on('fileuploaded', function(event, data, id, index) {
            var fname = data.files[index].name,
                out = '<li>' + 'U上传文件 # ' + (index + 1) + ' - '  +  
                    fname + ' 成功' + '</li>';
            $('#kv-success-1 ul').append(out);
            $('#kv-success-1').fadeIn('slow');
        });
    </script>
    
  9. 例11
    <input id="input-710" name="kartik-input-710[]" type="file" multiple class="file-loading">
    <div id="kv-error-2" style="margin-top:10px;display:none"></div>
    <script>
        <div id="kv-success-2" class="alert alert-success fade in" style="margin-top:10px;display:none"></div>
        $("#input-700").fileinput({
            uploadUrl: "http://localhost/file-upload-batch/1", // 服务器接收上传文件方法
            uploadAsync: false,
            showPreview: false,
            allowedFileExtensions: ['jpg', 'png', 'gif'],
            maxFileCount: 5,
            elErrorContainer: '#kv-error-2'
        }).on('filebatchpreupload', function(event, data, id, index) {
            $('#kv-success-2').html('<h4>上传状态</h4><ul></ul>').hide();
        }).on('filebatchuploadsuccess', function(event, data) {
            var out = '';
            $.each(data.files, function(key, file) {
                var fname = file.name;
                out = out + '<li>' + '上传文件 # ' + (key + 1) + ' - '  +  fname + ' 成功。' + '</li>';
            });
            $('#kv-success-2 ul').append(out);
            $('#kv-success-2').fadeIn('slow');
        });
    </script>
    
  10. 例12
    <input id="input-711" name="kartik-input-711[]" type="file" multiple class="file-loading">
    <script>
        $("#input-711").fileinput({
            uploadUrl: "http://localhost/file-upload-single/1", // 服务器接收上传文件方法
            uploadAsync: true,
            maxFileCount: 5,
            showBrowse: false,
            browseOnZoneClick: true
        });
    </script>
    

results matching ""

    No results matching ""