คุณสมบัติ (property) download ของ DOM Anchor Element (HTMLAnchorElement) ใช้ ตั้งค่า หรือ อ่านค่า ของแอตทริบิวต์ download ในแท็ก <a> ซึ่งระบุชื่อไฟล์เมื่อผู้ใช้ดาวน์โหลด
รูปแบบการใช้งาน (Syntax)
// ตั้งค่า (Setter)
anchorElement.download = "filename.ext";
// อ่านค่า (Getter)
const filename = anchorElement.download;
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<h2>ReactJS Logo Download</h2>
<!-- ลิงก์พร้อม download attribute -->
<a id="downloadLink"
href="https://www.tutorialspoint.com/images/reactjs.png"
download="ReactJS-Logo.png">
<img src="https://www.tutorialspoint.com/images/reactjs.png"
alt="ReactJS Logo"
width="200" height="200">
</a>
<br><br>
<button onclick="showDownloadValue()">แสดงค่า download attribute</button>
<p id="result"></p>
<script>
function showDownloadValue() {
const link = document.getElementById('downloadLink');
const filename = link.download; // อ่านค่า
document.getElementById('result').textContent =
'ชื่อไฟล์เมื่อดาวน์โหลด: ' + filename;
}
// ตัวอย่างการเปลี่ยนชื่อไฟล์ไดนามิก
function setCustomFilename() {
const link = document.getElementById('downloadLink');
const timestamp = new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-');
link.download = `ReactJS-Logo-${timestamp}.png`; // ตั้งค่าใหม่
console.log('เปลี่ยนชื่อไฟล์เป็น:', link.download);
}
</script>
</body>
</html>
พฤติกรรมที่สำคัญ
- Same-origin policy: download ทำงานเต็มที่เฉพาะ same-origin (โดเมน/พอร์ต/โปรโตคอลเดียวกัน) สำหรับ cross-origin จะขึ้นอยู่กับเบราว์เซอร์และ header
Content-Disposition - 副檔名 (extension): หากไม่ระบุ extension ใน download attribute เบราว์เซอร์อาจเพิ่มจาก Content-Type หรือ URL
- ค่าเริ่มต้น: หากไม่มี download attribute จะคืนค่า empty string
"" - Boolean behavior:
<a download>(ไม่มีค่า) = ใช้ชื่อไฟล์จาก URL
กรณีใช้งานจริง
- สร้างชื่อไฟล์ไดนามิก (timestamp, user ID, version)
- ดาวน์โหลดไฟล์ที่สร้างโดย JavaScript (Blob, Canvas, PDF generation)
- เปลี่ยนชื่อไฟล์ให้เข้าใจง่ายกว่า URL จริง
- บังคับให้ดาวน์โหลดแทนการเปิดในเบราว์เซอร์ (PDF, images, text)
ตัวอย่างขั้นสูง: ดาวน์โหลดข้อมูลที่สร้างโดย JS
function downloadAsFile(content, filename, mimeType = 'text/plain') {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Cleanup
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
}
// ใช้งาน
downloadAsFile('{"name":"John","age":30}', 'user-data.json', 'application/json');
downloadAsFile('Hello', 'page.html', 'text/html');