限制 JavaScript 中的文件大小上传

Limit file size upload in JavaScript

本文关键字:文件大小 JavaScript 限制      更新时间:2023-09-26

我正在尝试限制用户上传时文件的大小。我是 JavaScript 的新手,所以欢迎任何帮助。这就是我正在尝试的:

<input type="file" id="input_file" name="input_file" required maxlength="40" onchange="checkFileSize(this)" data-max_size="1048576" title="bla bla"
function checkFileSize(elem) {
var fsize = elem.files[0].size;
var fname = elem.files[0].name.length;
if (fsize > elem.getAttribute("data-max_size") || fname > elem.getAttribute("maxlength")) {
    elem.setCustomValidity(elem.getAttribute("title"));
} else {
    elem.setCustomValidity("");
}

}

当用户上传大于 1mb 的文件或文件名中有超过 40 个字符时,它不会触发 title(bla bla),什么都不会发生。我做错了什么?

您可以使用文件 API。

这是一个工作 jsfiddle 示例。用于验证的代码示例:

function showFileSize() {
    var input, file;
    // (Can't use `typeof FileReader === "function"` because apparently
    // it comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) {
        bodyAppend("p", "The file API isn't supported on this browser yet.");
        return;
    }
    input = document.getElementById('fileinput');
    if (!input) {
        bodyAppend("p", "Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
        bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
        bodyAppend("p", "Please select a file before clicking 'Load'");
    }
    else {
        file = input.files[0];
        // YOUR VALIDATION HERE USING file.size
        bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
    }
}

但请记住,客户端验证的存在只是为了通知/指导用户,您永远不应该依赖它在服务器中存储文件。

我已经将您的代码放入 JSBin - https://jsbin.com/rufigug/edit?html,js,console,output - 它似乎为我触发了正确的 IF 块,也许您可以控制台.log fname + fsize 并检查您的文件是否真的满足条件?

在MDN上有一些很好的文档 https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Limiting_the_size_of_a_file_before_its_upload

您正在使用事件onchange 。根据 http://www.w3schools.com/jsref/event_onchange.asp 的说法,它仅适用于<select>.

更改oninputonselect