
给定的脚本有效地验证文件类型合规性。要额外验证文件大小并防止上传超过 500kB,请考虑以下解决方案:
在用户选择文件时利用 HTML5 文件 API 确定文件大小:
<code class="javascript">document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);利用 $_FILES 数组检索服务器上的文件大小:
<code class="php">if(isset($_FILES['file'])) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}</code>如果必要时,使用 upload_max_filesize ini 设置将上传限制为适合所有场景的值。请注意,这是一个全局设置。
客户端验证通过防止不必要的上传并提醒用户文件问题来提供用户友好的体验。服务器端验证对于确保安全性仍然至关重要,因为客户端检查可能会受到损害。
以上是如何在上传前验证文件大小:客户端与服务器端?的详细内容。更多信息请关注PHP中文网其他相关文章!