javascript – 我们可以使用msgSizeTooLarge选项以MB为单位显示有关fileinput插件的错误消息

关于文件输入插件( http://plugins.krajee.com/file-input).

我们能以MB显示文件大小错误消息吗?有一个选项可以自定义错误消息,但我找不到以MB而不是KB显示大小.

msgSizetooLarge

File “{name}” ({size} KB) exceeds maximum allowed upload size of
{maxSize} KB. Please retry your upload!

任何显示MB大小的解决方案?

解决方法

非常棘手的事情,因为 Bootstrap File Input插件没有这样的扩展功能.但是,嘿,一切都可以在Javascript中完成!

为了更改验证错误消息,您必须向fileuploaderror事件添加处理程序(可能您必须根据您的需要和设置捕获一些其他错误.对于完整错误支持的事件,请参阅here).然后将msgSizetooLarge选项字符串格式化为我们想要的.我们需要为msgSizetooLarge提供一个带有字符串键名的自定义格式;对于{size},它将是{customSize},对于{maxSize},它将是{customMaxSize}. msgSizetooLarge消息将如下所示:

msgSizetooLarge: 'File "{name}" (<b>{customSize}</b>) exceeds maximum allowed upload size of <b>{customMaxSize}</b>. Please retry your upload!'

获取文件大小,您将使用传递给fileuploaderror事件的data参数并使用第一个文件大小size = data.files [0] .size.对于maxFileSize,您只需读取元素数据,其中存储了所有fileinputs的数据maxFileSize = $(this).data().fileinput.maxFileSize.现在,我们只创建一个简单的函数将字节转换为正确的格式,或者您甚至可以更改它并强制它始终显示MB格式化值. formatSize函数将是这样的:

formatSize = (s) => {
    i = Math.floor(Math.log(s) / Math.log(1024));
    sizes = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
    out = (s / Math.pow(1024,i)).toFixed(2) * 1 + ' ' + sizes[i];
    return out;
};

然后我们使用replace函数替换我们的字符串键,格式化文件大小:

msg = msg.replace('{customSize}',formatSize(size));
msg = msg.replace('{customMaxSize}',formatSize(maxFileSize * 1024 /* Convert KB to Bytes */));

结果错误消息将是这样的:

File “Endless Dream.mp3” (2.07 MB) exceeds maximum allowed upload size of 2 MB. Please retry your upload!

最后,我们使用data.id来更改< li>元素错误文本到我们现在拥有的:

$('li[data-file-id="'+data.id+'"]').html(msg);

结果消息:

Bootrstrap File Input Screenshot

您可以测试我的示例here.最大文件大小为2MB.

我的全部工作javascript代码

$("#file-1").fileinput({
    uploadUrl: '#',// you must set a valid URL here else you will get an error
    overwriteInitial: false,maxFileSize: 2048,// 2028 KB == 2 MB
    msgSizetooLarge: 'File "{name}" (<b>{customSize}</b>) exceeds maximum allowed upload size of <b>{customMaxSize}</b>. Please retry your upload!'
}).on('fileuploaderror',function(event,data,msg) {
    var size = data.files[0].size,maxFileSize = $(this).data().fileinput.maxFileSize,formatSize = (s) => {
            i = Math.floor(Math.log(s) / Math.log(1024));
            sizes = ['B','YB'];
            out = (s / Math.pow(1024,i)).toFixed(2) * 1 + ' ' + sizes[i];
            return out;
        };

    msg = msg.replace('{customSize}',formatSize(size));
    msg = msg.replace('{customMaxSize}',formatSize(maxFileSize * 1024 /* Convert KB to Bytes */));
    $('li[data-file-id="'+data.id+'"]').html(msg);
});

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...