2/11/2557

การอ่านและแสดงไฟล์รูปที่ upload ด้วย FileReader (HTML5)

 
HTML5 ได้เพิ่มความสามารถให้เราอ่านไฟล์ที่ upload ได้ เราสามารถนำมาประยุต์ใช้เพื่อแสดงรูปภาพที่ผู้ใช้ upload มาทันทีโดยไม่ต้องทำงานที่ฝั่ง server ดังนี้

<input type='file'  onchange='openFile(event)'>
<!-- สร้าง Element สำหรับ Upload ไฟล์ โดยกำหนดให้ทำงานที่ function openFile เมื่อ User Upload  -->
<br />
<img id='output'><!-- สร้าง Element แสดงไฟล์ที่ User Upload -ขึ้นมา -->
<script>
    var openFile = function(event) { // สร้าง function openFile
    var reader = new FileReader(); //สร้าง object สำหรับ อ่านไฟล์
    reader.onload = function(event){//สั่งให้เริ่มอ่านไฟล์เมื่อมีการสรั้าง object  FileReader
        var dataURL = event.target.result;//อ่านไฟล์ที่ Upload
        document.getElementById('output').src = dataURL; //แสดงไฟล์ใน Element img
    };
    reader.readAsDataURL(event.target.files[0]);
  };
</script>