简体   繁体   English

没有文件API的Javascript文件大小验证

[英]Javascript File size validation without File API

Do we have any way using which we can validate File Size before upload in Javascript other then using File API as that is not supported in IE8 and 9. 除了在IE8和9中不支持的文件API之外,是否还有其他方法可以使用Java API上载之前验证文件大小的方法?

Files are being selected with file type input tag 使用文件类型输入标签选择文件

Dont want to use Activex 不想使用Activex

You can use a polyfill to add support for File API in older browsers such as IE8 and IE9. 您可以使用polyfill在旧版浏览器(例如IE8和IE9)中添加对File API的支持。

Go here and scroll down to the "File API" section. 转到此处并向下滚动到“文件API”部分。

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

You can do this using Javascript as shown below, 您可以使用Javascript来执行此操作,如下所示,

    $('input[type="file"]').change(function () {
    if (this.files[0] != undefined) {
        var name = this.name;
        var filesize = this.files[0].size;
        var field = $('#' + this.name).parents('.input-group');

        //check if file size is larger than 3MB(which is 3e+6 bytes)
        if (filesize > 3000000) {
           alert(filesize);
        //reset that input field if its file size is more than 3MB
           $('[name="' + name + '"]').val('')
        }
    }
});

you can just include this for all input of type='file' by changing size limit in bytes. 您可以通过更改大小限制(以字节为单位)将其包括在type ='file'的所有输入中。

Active X (haters gonna hate): Active X(讨厌的人会讨厌):

var filepath = 'path/to/file',
    fso = new ActiveXObject('Scripting.FileSystemObject'),
    file = fso.getFile(filepath),
    imgbytes = file.size;

console.log(imgbytes);

Not that I know. 不,我知道。 Anyway, as client validation is only for user-friendlyness purposes, you could easilly fall back to a check on the server if your user doesn't have a browser supporting file API. 无论如何,由于客户端验证仅出于用户友好性目的,如果您的用户没有支持文件API的浏览器,则可以轻松地回到服务器上进行检查。 With old browsers they should be used to get less user-friendly sites anyway... 在旧的浏览器中,无论如何,它们都应该用来获取不太友好的网站...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM