zoukankan      html  css  js  c++  java
  • bootstrap-fileinput上传文件的插件使用总结----编辑已成功上传过的图片

    http://plugins.krajee.com/file-plugin-methods-demo 具体操作

    http://plugins.krajee.com/file-preview-management-demo

    bootstrap-fileinput上传文件的插件使用总结----编辑已成功上传过的图片

    这里所讲述的是:编辑已成功上传过的图片

     参考:Initial Preview Data  http://plugins.krajee.com/file-preview-management-demo

    下面标记红色的部<!-- PREVIEW DATA -->

    <!-- PREVIEW DATA -->
    <!-- load the JS files in the right order -->
    <!-- sortable plugin for sorting/rearranging initial preview -->
    <script src="/path/to/js/plugins/sortable.min.js"></script>
    <!-- purify plugin for safe rendering HTML content in preview -->
    <script src="/path/to/js/plugins/purify.min.js"></script>
    <script src="/path/to/js/fileinput.js"></script>
    
    
    <div class="file-loading">
        <input id="input-pd" name="input-pd[]" type="file" multiple>
    </div>
    <script>
    $("#input-pd").fileinput({
        uploadUrl: "/file-upload-batch/1",
        uploadAsync: false,
        minFileCount: 2,
        maxFileCount: 5,
        overwriteInitial: false,
        initialPreview: [
            // IMAGE DATA
            "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Desert.jpg",
            // IMAGE DATA
            "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Lighthouse.jpg",
            // VIDEO DATA
            "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/small.mp4",
            // OFFICE WORD DATA
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/SampleDOCFile_100kb.doc',
            // OFFICE EXCEL DATA
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/SampleXLSFile_38kb.xls',
            // OFFICE POWERPOINT DATA
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/SamplePPTFile_500kb.ppt',
            // TIFF IMAGE FILE
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/multipage_tiff_example.tif',
            // ADOBE ILLUSTRATOR FILE
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/sample_ai.ai',
            // ENCAPSULATED POST SCRIPT FILE
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/sample_eps.eps',
            // PDF DATA
            'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/pdf-sample.pdf',
            // TEXT DATA
            "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 DATA '<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>' + '</div>' ], initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup initialPreviewFileType: 'image', // image is the default and can be overridden in config below initialPreviewDownloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/{filename}',
      // includes the dynamic `filename` tag to be replaced for each config initialPreviewConfig: [ {caption: "Desert.jpg", size: 827000, "120px", url: "/file-upload-batch/2", key: 1}, {caption: "Lighthouse.jpg", size: 549000, "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, downloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/small.mp4', // override url filename: 'KrajeeSample.mp4' // override download filename }, {type: "office", size: 102400, caption: "SampleDOCFile_100kb.doc", url: "/file-upload-batch/2", key: 4}, {type: "office", size: 45056, caption: "SampleXLSFile_38kb.xls", url: "/file-upload-batch/2", key: 5}, {type: "office", size: 512000, caption: "SamplePPTFile_500kb.ppt", url: "/file-upload-batch/2", key: 6}, {type: "office", size: 811008, caption: "multipage_tiff_example.tif", url: "/file-upload-batch/2", key: 7}, {type: "office", size: 375808, caption: "sample_ai.ai", url: "/file-upload-batch/2", key: 8}, {type: "office", size: 40960, caption: "sample_eps.eps", url: "/file-upload-batch/2", key: 9}, {type: "pdf", size: 8000, caption: "About.pdf", url: "/file-upload-batch/2", key: 10, downloadUrl: false}, // disable download {type: "text", size: 1430, caption: "LoremIpsum.txt", url: "/file-upload-batch/2", key: 11, downloadUrl: false}, // disable download {type: "html", size: 3550, caption: "LoremIpsum.html", url: "/file-upload-batch/2", key: 12, downloadUrl: false} // disable download ], purifyHtml: true, // this by default purifies HTML data for preview 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>
    
    

    //编辑文件上传 插件初始化    通过封装的方式可以 减少很多重复的代码  

    //initialPreviewDownloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/{filename}', // includes the dynamic `filename` tag to be replaced for each config
    initialPreviewDownloadUrl: $("#SourcePath").val(),
    initialPreviewConfig: [{ caption: $("#SourceName").val(), size: 827000, "120px",url: "/source/delete",key: 1 },], 额外数据上文中的uploadExtraData


     

    //编辑

    1. function edit(id) {
    2. $.ajax({
    3. type: "Get",
    4. url: "/Source/Get?id=" + id + "&_t=" + new Date().getTime(),
    5. success: function (data) {
    6. $("#Id").val(data.id);
    7. $("#SourceName").val(data.sourceName);
    8. $("#SourceType").val(data.sourceTypeEnum);
    9. $("#Suffix").val(data.suffixEnum);
    10. $("#SourcePath").val(data.sourcePath);
    11. $("#SourceContentMD5").val(data.sourceContentMD5);
    12. var divParent = $('#uploadfile').parents('.col-sm-10').empty();
    13. var pwd = $("<input id='uploadfile' type='file'>");
    14. divParent.append(pwd);
    15. var control = $('#uploadfile');
    16. control.fileinput({
    17. 'showUpload': true,
    18. 'previewFileType': 'any',
    19. language: 'zh',
    20. allowedFileExtensions: ['jpg', 'png', 'jpeg', 'bmp', 'mp4', 'avi', 'mov', 'wmv', '3gp', 'rmvb', 'asf', 'fla', 'swf', 'apk'],
    21. uploadUrl: '/Source/UploadSource',
    22. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash'],
    23. overwriteInitial: true,
    24. initialPreview: [$("#SourcePath").val(),],
    25. initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
    26. //initialPreviewDownloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/{filename}', // includes the dynamic `filename` tag to be replaced for each config
    27. initialPreviewDownloadUrl: $("#SourcePath").val(),
    28. initialPreviewConfig: [
    29. { caption: $("#SourceName").val(), size: 827000, "120px", key: 1 },
    30. ],
    31. });
    32. $('#uploadfile').on('fileselect', function (event, numFiles, label) {
    33. var arr = ["image", "video", "application"];
    34. var type;
    35. files = $('#uploadfile').fileinput('getFileStack');
    36. var index1 = label.lastIndexOf(".");
    37. var index2 = label.length;
    38. var suffix = label.substring(index1 + 1, index2);//后缀名
    39. var name = label.substring(0, index1);
    40. $("#SourceName").val(name);
    41. for (var i = 0; i < arr.length; i++) {
    42. if (files[0].type.indexOf(arr[i]) >= 0) {
    43. if (arr[i] == "image") {
    44. type = "图片";
    45. }
    46. else if (arr[i] == "video") {
    47. type = "视频";
    48. }
    49. else if (arr[i] == "application") {
    50. type = "apk";
    51. }
    52. else {
    53. type = "其他";
    54. }
    55. break;
    56. }
    57. }
    58. $("#SourceType").val(type);
    59. $("#Suffix").val(suffix);
    60. getFilemd5(files[0]);
    61. }).on('fileuploaded', function (event, data, previewId, index) {
    62. if (data.response.success) {
    63. console.log('fileuploaded');
    64. var fileurl = data.response.data;
    65. var md5message = data.response.message;
    66. if (fileurl) {
    67. var postData = {
    68. "sou": {
    69. "Id": $("#Id").val(), "SourceName": $("#SourceName").val(),
    70. "SourceTypeEnum": $("#SourceType").val(),
    71. "SuffixEnum": $("#Suffix").val(),
    72. "SourcePath": fileurl, "OrganizationID": selectedId,
    73. "SourceContentMD5": md5message
    74. }
    75. };
    76. $.ajax({
    77. type: "Post",
    78. url: "/Source/Edit",
    79. data: postData,
    80. success: function (data) {
    81. if (data.success) {
    82. $('#uploadfile').fileinput('clear');
    83. loadTables(1, 10);
    84. $("#editModal").modal("hide");
    85. } else {
    86. layer.tips(data.message, "#btnSave");
    87. };
    88. }
    89. });
    90. }
    91. else {
    92. }
    93. }
    94. }).on("filecleared", function (event, data, msg) {
    95. $("#Id").val("0");
    96. $("#SourceName").val("");
    97. $("#SourceType").val("");
    98. $("#Suffix").val("");
    99. $("#SourcePath").val("");
    100. $("#OrganizationID").val("");
    101. $("#SourceContentMD5").val("");
    102. }).on("fileremoved", function (event, data, msg) {
    103. $("#Id").val("0");
    104. $("#SourceName").val("");
    105. $("#SourceType").val("");
    106. $("#Suffix").val("");
    107. $("#SourcePath").val("");
    108. $("#OrganizationID").val("");
    109. $("#SourceContentMD5").val("");
    110. });
    111. //var roleIds = [];
    112. //if (data.userInRole) {
    113. // $.each(data.userInRole, function (i, item) {
    114. // roleIds.push(item.rolesID)
    115. // });
    116. // $("#Role").select2("val", roleIds);
    117. //}
    118. $("#Title").text("编辑资源")
    119. $("#editModal").modal("show");
    120. }
    121. });
    122. };

    下面是参数初始化设置说明

    function edit_image(path,con){  

            $("#upload").fileinput({  

                 uploadUrl: "upload", //上传到后台处理的方法  

                 uploadAsync: false, //设置同步,异步 (同步)  

                 language: 'zh', //设置语言  

                 overwriteInitial: false, //不覆盖已存在的图片  

                //下面几个就是初始化预览图片的配置      

                 initialPreviewAsData: true,  

                 initialPreviewFileType: 'image',  

                 initialPreview:path , //要显示的图片的路径  

                 initialPreviewConfig:con  

            });   

    }

     

    接下来 通过ajax向后台请求对应的编辑的图片数据组装数组传入到 上面的方法中  

    就可以在页面上显示了  

    注:在 ajax中 初始化 fileinput 是配置参数是不起作用的  需要 先销毁,再初始化  

    1、销毁fileinput  见官网 http://plugins.krajee.com/file-plugin-methods-demo  

      $("#upload").fileinput('destroy');  

         //初始化方法   

            edit_image();  

    相关配置见官网  

    <target=_blank href="http://plugins.krajee.com/file-input-ajax-demo/3" target="_blank">点击打开链接</a

     

    2、销毁fileinput另外一种是先根据上传控件找到上传控件的父节点,然后删除上传控件节点,然后再重新创建一个上传控件,并添加到父节点中,

    html 代码如下:

    1. <div class="form-group">
    2. <label class="col-sm-2 control-label" for="inputPassword3">选择资源</label>
    3. <div class="col-sm-10">
    4. <input id="uploadfile" type="file">
    5. </div>
    6. </div>

     

    jquery 代码如下:

    1. var divParent = $('#uploadfile').parents('.col-sm-10').empty();
    2. var pwd = $("<input id='uploadfile' type='file'>");
    3. divParent.append(pwd);
    4. var control = $('#uploadfile');
    5. control.fileinput({
    6. 'showUpload': true,
    7. 'previewFileType': 'any',
    8. language: 'zh',
    9. allowedFileExtensions: ['jpg', 'png', 'jpeg', 'bmp', 'mp4', 'avi', 'mov', 'wmv', '3gp', 'rmvb', 'asf', 'fla', 'swf', 'apk'],
    10. uploadUrl: '/Source/UploadSource',
    11. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash'],
    12. overwriteInitial: true,
    13. initialPreview: [$("#SourcePath").val(),],
    14. initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
    15. //initialPreviewDownloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/{filename}', // includes the dynamic `filename` tag to be replaced for each config
    16. initialPreviewDownloadUrl: $("#SourcePath").val(),
    17. initialPreviewConfig: [
    18. { caption: $("#SourceName").val(), size: 827000, "120px", key: 1 },
    19. ],
    20. });

    参考链接:

    http://blog.csdn.net/sinat_33750162/article/details/51497563

    http://plugins.krajee.com/file-plugin-methods-demo

    http://plugins.krajee.com/file-preview-management-demo

  • 相关阅读:
    iOS有用的三方库和高效工具记录
    正则表达式
    Exception Type & Exception Code
    信鸽推送(XGPush)
    在vue中使用animate.css
    vue 中父子组件传值:props和$emit
    预编译scss以及scss和less px 转rem
    ES6箭头函数及模版字符串
    移动端页面a input去除点击效果及pc端切换
    vue2搭建简易spa
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/8534175.html
Copyright © 2011-2022 走看看