有没有办法在使用 JavaScript 上传文件之前检查文件大小?
JavaScript 文件上传大小验证
IT技术
javascript
validation
file-upload
2021-01-19 09:20:33
6个回答
是的,您可以为此使用File API。
这是一个完整的例子(见评论):
document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
// (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) { // This is VERY unlikely, browser support is near-universal
console.log("The file API isn't supported on this browser yet.");
return;
}
var input = document.getElementById('fileinput');
if (!input.files) { // This is VERY unlikely, browser support is near-universal
console.error("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
addPara("Please select a file before clicking 'Load'");
} else {
var file = input.files[0];
addPara("File " + file.name + " is " + file.size + " bytes in size");
}
});
function addPara(text) {
var p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
}
body {
font-family: sans-serif;
}
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>
稍微偏离主题,但是:请注意,客户端验证不能替代服务器端验证。客户端验证纯粹是为了提供更好的用户体验。例如,如果您不允许上传超过 5MB 的文件,您可以使用客户端验证来检查用户选择的文件大小是否不超过 5MB,如果是,则给他们一个友好的消息(因此他们不会花费所有时间上传只是为了将结果扔到服务器上),但是您还必须在服务器上强制执行该限制,因为可以规避所有客户端限制(和其他验证)。
使用jQuery:
$('#image-file').on('change', function() {
console.log('This file size is: ' + this.files[0].size / 1024 / 1024 + "MiB");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form action="upload" enctype="multipart/form-data" method="post">
Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />
</form>
适用于动态和静态文件元素
仅Javascript解决方案
function validateSize(input) {
const fileSize = input.files[0].size / 1024 / 1024; // in MiB
if (fileSize > 2) {
alert('File size exceeds 2 MiB');
// $(file).val(''); //for clearing with Jquery
} else {
// Proceed further
}
}
<input onchange="validateSize(this)" type="file">
这很简单。
const oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>
if (oFile.size > 2097152) // 2 MiB for bytes.
{
alert("File size must under 2MiB!");
return;
}
否是,在较新的浏览器中使用 File API。有关详细信息,请参阅 TJ 的回答。
如果您还需要支持旧版浏览器,则必须使用基于 Flash 的上传器(如SWFUpload或Uploadify)来执行此操作。
该SWFUpload的功能演示显示了如何file_size_limit
设置工作。
请注意,这(显然)需要 Flash,而且它的工作方式与普通上传表单略有不同。
其它你可能感兴趣的问题