Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

HTML5 อนุญาตให้โต้ตอบกับ Local Client Files จาก Web Browser ได้หรือไม่?

ไม่สามารถเข้าถึงไฟล์โดยตรงได้ (Security Sandbox)

HTML5 **ไม่สามารถ** อ่าน/เขียนไฟล์บนเครื่องผู้ใช้โดยตรง ต้องผ่าน API ที่ผู้ใช้ต้องกระทำ (User Interaction)

วิธีที่อนุญาต

  • Drag and Drop API - ผู้ใช้ลากไฟล์มาวางบนเบราว์เซอร์
  • File Input (<input type="file">) - ผู้ใช้เลือกไฟล์ผ่านไดอะล็อก
  • FileSystem API (Deprecated/Non-standard) - Sandboxed filesystem (Chrome เท่านั้น)

ตัวอย่าง Drag and Drop

<div id="boxA" draggable="true" ondragstart="dragStart(event)">Drag Me</div>
<div id="boxB">Drop Zone</div>

<script>
function dragStart(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}
</script>

ทุกการเข้าถึงต้องมี User Gesture (คลิก, ลาก, วาง) ไม่สามารถอ่านไฟล์อัตโนมัติได้