服务端无法瞬间就得到文件大小,因为他是流传输,需要等累积到一定的大小,超过系统限制了才会抛异常。
你的问题可以通过前端来解决,因为前端可直接调用文件API获取大小。前端设置大小限制后,上传前进行判断即可。
大概的伪代码如图,可参考应用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传前端验证</title>
</head>
<body>
<h2>请选择一个文件上传(限制1GB)</h2>
<input type="file" id="fileInput">
<button onclick="uploadFile()">上传</button>
<div id="errorMessage" style="color: red; margin-top: 10px;"></div>
<script>
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const errorDiv = document.getElementById('errorMessage');
// 清空之前的错误信息
errorDiv.textContent = '';
// 检查用户是否选择了文件
if (fileInput.files.length === 0) {
errorDiv.textContent = '请先选择一个文件!';
return;
}
const file = fileInput.files[0];
// 定义最大文件大小(1GB,单位:字节)
// 1GB = 1024 * 1024 * 1024 Bytes
const MAX_SIZE_IN_BYTES = 1 * 1024 * 1024 * 1024;
console.log(`文件大小: ${file.size} 字节`);
// 判断文件大小
if (file.size > MAX_SIZE_IN_BYTES) {
errorDiv.textContent = `上传失败:文件大小为 ${(file.size / 1024 / 1024).toFixed(2)} MB,超过了1GB的限制。`;
// 阻止上传
return;
}
// --- 文件大小验证通过,可以在这里执行真正的上传逻辑 ---
console.log('文件验证通过,开始执行上传...');
alert('文件验证通过,准备上传!');
// 示例:使用 FormData 和 fetch API 上传文件
const formData = new FormData();
formData.append('file', file);
/*
fetch('/your/upload/endpoint', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log('上传成功:', data))
.catch(error => console.error('上传失败:', error));
*/
}
</script>
</body>
</html>
扫一扫访问 Blade技术社区 移动端