js中如何在浏览器判断上传文件的大小?


项目需要上传文件,我们的做法是在后端判断,这样效果很不好。如果文件太大,要等到上传完才能发现。请问可否在前端的js中直接判断文件大小呢?这样,如果文件太大,就不上传了。谢谢

开发 js JavaScript 文件大小判断

s惊蛰小满s 10 years, 3 months ago

当然可以,假设你的文件字段id为 id_file,可以参考以下代码:

document.getElementById('id_file').addEventListener('change', checkFile, false);

function checkFile(e) {
    var file_list = e.target.files;
        var max_upload_size = 10*1024*1024; //10MB
    for (var i = 0, file; file = file_list[i]; i++) {
        var fileExtension = file.name.split('.')[file.name.split('.').length - 1].toLowerCase();
        var iConvert = (file.size / 1024).toFixed(2);

        txt = "File type : " +fileExtension + "\n";
        if(file.size > max_upload_size){
            txt += "Size: " + (file.size / (1024*1024)).toFixed(2) + " MB \n超过了"+ (max_upload_size/1024/1024).toFixed(2) + " MB 的文件上限,请压缩";
            $('#id_file').val('');
            $('#id_file').attr('disabled', 'disabled');
            alert(txt);
        } 
    }
}

也可以尝试以下代码:

function IsFileSizeOk(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if (navigator.userAgent.match(/msie/i)) {
            //before making an object of ActiveXObject, 
            //please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in kb
            fileSize = fileSize / 1048576; //size in mb 
        }
            //for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in kb
            fileSize = fileSize / 1048576; //size in mb 
        }
        return (fileSize < 2.0);
    }
    catch (e) {
        alert("Error is :" + e);
    }
}
你们亲爱的熊哥 answered 10 years, 3 months ago

Your Answer