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

HTML DOM Input FileUpload value Property: ค่าเส้นทางไฟล์

คุณสมบัติ value ของ file upload คืนค่าเส้นทางไฟล์ที่เลือก (รูปแบบ C:\fakepath\filename.ext เพื่อความปลอดภัย)

รูปแบบ (Syntax)

object.value

ตัวอย่างการใช้งาน

แสดงค่า value ของ file input เมื่อคลิกปุ่ม:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { background-color: #397367; color: #fff; padding: 20px; }
        .btn { display: block; background-color: #22223B; color: #fff; border: none; padding: 0.5rem; border-radius: 50px; width: 80%; margin: 10px; }
        .show-value { font-weight: bold; font-size: 1.4rem; color: #fff; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง FileUpload value Property</h1>
    <p>กรุณาเลือกไฟล์!</p>
    <input type="file">
    <button onclick="getValue()" class="btn">ดูค่า value ของ file input</button>
    <div class="show-value"></div>
    <script>
        function getValue() {
            var chooseFileBtn = document.querySelector("input");
            document.querySelector(".show-value").innerHTML = "Value = " + chooseFileBtn.value;
        }
    </script>
</body>
</html>

ข้อจำกัดด้านความปลอดภัย

  • ไม่สามารถอ่านเส้นทางจริงของไฟล์บนเครื่องผู้ใช้ได้ (security sandbox)
  • ค่าจะอยู่ในรูปแบบ C:\fakepath\filename.ext เสมอ
  • ไม่สามารถกำหนดค่า value ผ่าน JavaScript ได้ (read-only)

ทางเลือกที่ดีกว่า: ใช้ files property

แทนที่จะใช้ value ให้ใช้ files property เพื่อเข้าถึงข้อมูลไฟล์จริง:

var file = fileInput.files[0];
console.log(file.name, file.size, file.type, file.lastModified);