File.size Property คืออะไร?
File.size คืนค่าขนาดไฟล์ในหน่วย Bytes (ไบต์) เป็นตัวเลขจำนวนเต็ม (integer) Read-only property
- ค่า 0 = ไฟล์ว่างเปล่า
- ใช้สำหรับ validation ขนาดไฟล์ก่อนอัปโหลด
- รองรับในทุกเบราว์เซอร์สมัยใหม่
ตัวอย่างโค้ดครบถ้วน
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>File.size Demo</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; max-width: 700px; margin: 0 auto; }
.drop-zone { border: 3px dashed #2196F3; border-radius: 12px; padding: 40px; text-align: center; margin: 20px 0; cursor: pointer; transition: all 0.2s; }
.drop-zone.drag-over { border-color: #4CAF50; background: #e8f5e9; }
.drop-zone input { display: none; }
.file-card { background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 20px; margin: 15px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
.file-card.error { border-color: #f44336; background: #fdeaea; }
.file-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
.file-name { font-weight: 600; color: #333; word-break: break-all; }
.file-size { font-family: monospace; font-size: 18px; font-weight: bold; color: #2196F3; }
.file-size.error { color: #f44336; }
.progress-bar { height: 8px; background: #eee; border-radius: 4px; overflow: hidden; margin-top: 15px; }
.progress-fill { height: 100%; background: linear-gradient(90deg, #4CAF50, #8BC34A); border-radius: 4px; transition: width 0.3s; }
.progress-fill.error { background: linear-gradient(90deg, #f44336, #ff7043); }
.meta { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-top: 15px; font-size: 14px; color: #666; }
.meta span { background: #f5f5f5; padding: 8px; border-radius: 4px; }
.meta strong { color: #333; display: block; margin-bottom: 4px; }
</style>
</head>
<body>
<h1>ตรวจสอบขนาดไฟล์ (File.size)</h1>
<p>ลากไฟล์มาวาง หรือคลิกเลือกได้หลายไฟล์พร้อมกัน</p>
<div class="drop-zone" id="dropZone">
<input type="file" id="fileInput" multiple />
<div>📁 ลากไฟล์มาวางที่นี่ หรือคลิกเพื่อเลือก</div>
<small>รองรับหลายไฟล์พร้อมกัน & แสดง Progress bar แสดงสัดส่วนขนาด</small>
</div>
<div id="fileContainer"></div>
<script>
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const container = document.getElementById('fileContainer');
const MAX_SIZE = 10 * 1024 * 1024; // 10MB limit for demo
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); handleFiles(e.dataTransfer.files); });
fileInput.addEventListener('change', (e) => handleFiles(e.target.files));
function handleFiles(files) {
container.innerHTML = '';
Array.from(files).forEach(file => renderFileCard(file));
}
function renderFileCard(file) {
const size = file.size;
const formattedSize = formatFileSize(size);
const percent = Math.min((size / MAX_SIZE) * 100, 100);
const isError = size > MAX_SIZE;
const card = document.createElement('div');
card.className = 'file-card' + (isError ? ' error' : '');
card.innerHTML = `
${escapeHtml(file.name)}
${formattedSize}
`;
container.appendChild(card);
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
</script>
</body>
</html>
การแปลงหน่วยขนาดไฟล์
| หน่วย | ค่า (Bytes) | ตัวอย่าง |
|---|---|---|
| Bytes (B) | 1 | 500 B |
| Kilobytes (KB) | 1,024 | 1.5 KB |
| Megabytes (MB) | 1,048,576 | 2.3 MB |
| Gigabytes (GB) | 1,073,741,824 | 4.7 GB |
| Terabytes (TB) | 1,099,511,627,776 | 1.2 TB |
ฟังก์ชัน Format ขนาดไฟล์ (Reusable)
function formatFileSize(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// ใช้งาน
console.log(formatFileSize(1500)); // "1.46 KB"
console.log(formatFileSize(1500000)); // "1.43 MB"
console.log(formatFileSize(1500000000)); // "1.40 GB"
การ Validate ขนาดไฟล์ (File Size Validation)
Client-side (JavaScript)
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
function validateFileSize(file) {
if (file.size > MAX_FILE_SIZE) {
throw new Error(`ไฟล์ "${file.name}" มีขนาด ${formatFileSize(file.size)} เกินขนาดสูงสุด ${formatFileSize(MAX_FILE_SIZE)}`);
}
return true;
}
// ใช้กับ multiple files
function validateFiles(files) {
const errors = [];
Array.from(files).forEach(file => {
if (file.size > MAX_FILE_SIZE) {
errors.push(`${file.name}: ${formatFileSize(file.size)} (max ${formatFileSize(MAX_FILE_SIZE)})`);
}
});
return errors;
}
Server-side (Node.js/Express + Multer)
const multer = require('multer');
const upload = multer({
limits: {
fileSize: 5 * 1024 * 1024, // 5MB
files: 10 // max 10 files
},
fileFilter: (req, file, cb) => {
// ตรวจสอบ MIME type ด้วย
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!allowedTypes.includes(file.mimetype)) {
return cb(new Error('ประเภทไฟล์ไม่รองรับ'), false);
}
cb(null, true);
}
});
app.post('/upload', upload.array('files'), (req, res) => {
// req.files มีข้อมูลไฟล์ที่ผ่าน validation แล้ว
});
ข้อควรระวัง
File.sizeเป็นขนาดไฟล์จริง (Raw bytes) ไม่ใช่ขนาดหลายอัปโหลด (Base64 encoding เพิ่ม ~33%)- สำหรับไฟล์ใหญ่ (> 2GB) ใช้
File.prototype.sizeได้ปกติ (รองรับ 64-bit integer) - Blob ก็มี property
.sizeเช่นกัน - การอ่านขนาดไฟล์ไม่ได้อ่านเนื้อหาไฟล์ (Fast, ไม่ใช้ memory)