ruoyi内置bootstrap-fileinput上传控件实现上传后拖拽排序

bootstrap-fileinput项目地址:

请点这里

bootstrap-fileinput官方演示地址:

请点这里

说明

使用的是ruoyi的前后端不分离版本,官网说明文档比较简略,所以研究了下上传控件的官方文档,文档地址:请点这里
上传控件版本:bootstrap-fileinput v5.0.4

需求

  1. 已上传文件需要支持拖拽排序
  2. 新上传的文件,上传成功后也要支持拖拽排序

分析

bootstrap-fileinput组件是默认支持拖拽排序的,但是这个操作,只能是在配置了 initialPreview 参数的情况下。 等于说是每次上传成功后需要更新initialPreview的值,且需要刷新bootstrap-fileinput组件。

通过阅读官方文档,可以知道,自从 v4.4.x版本之后,refresh方法已经没法做到刷新上传组件的预览配置了,需要先调用destroy方法,再重新初始化组件才可以。

Note
The refresh method cannot be used to update the initialPreview or initialPreviewConfig since v4.4.x. In case you need to replace initialPreview, then use the plugin's destroy method instead and then reinitialize the plugin with the new options. Note that when reinitializing after a destroy, you must provide all the options for the plugin to reinitialize (unlike the refresh).

点这精准空降文档

代码如下

var vals=[]; // 这个是已上传的文件列表,根据自己需要更改
var options ={
            'uploadUrl': 【上传地址】,
            initialPreviewAsData: true,
            initialPreview: vals,
            maxFileCount: 6,
            overwriteInitial: false,
             // 是否显示上传按钮,这个需要禁用,我的代码有个bug,destroy再初始化后上传按钮失效了
             // 只能禁用后使用上传列表的文件缩略图下面的上传按钮上传
            showUpload: false,
            showCaption: true,//是否显示标题
            allowedFileExtensions: ["png", "jpg", "gif"],
        };
        $(【组件id】).fileinput(options).on('fileuploaded', function (event, data, previewId, index) {
            if(data.response.code==500){
                $(【组件id】).fileinput('reset');
                $.modal.alertError(data.response.msg);
            }
            // 重置上传组件,保证新上传的文件也能拖拽排序
            vals.push(data.response.url);
            options.initialPreview = vals;
            $(【组件id】).fileinput('destroy').fileinput(options);
        }).on('fileremoved', function (event, id, index) {
           
        })
        $(【组件id】).fileinput('_initFileActions');

        // 监听拖拽排序的事件
         $(【组件id】).on('filesorted', function(event, params) {
            // 获取预览图的当前顺序
            $(【组件id】).fileinput('getPreview').content.forEach(function(item){
              	【执行你需要的操作】
            });
         });

核心是如下的代码:

vals.push(data.response.url); // 将新上传成功的文件放到文件列表里
options.initialPreview = vals; // 为bootstrap-fileinput组件的配置项中的initialPreview配置新的值
$(【组件id】).fileinput('destroy').fileinput(options); // 先销毁fileinput组件,再用新的配置项重新初始化

tips

如果你的上传组件不支持拖拽,那就是没有引入必需的依赖组件,需要再引入 plugins下的 piexif.min.jssortable.min.js 引入后即可使用拖拽功能
注意选择正确的版本,可以切换代码库的tag版本

# jQuery 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×