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

แอตทริบิวต์ enctype ใน HTML: รูปแบบการเข้ารหัสข้อมูลฟอร์ม

แอตทริบิวต์ enctype คืออะไร?

แอตทริบิวต์ enctype ใน HTML ใช้ระบุรูปแบบการเข้ารหัส (Encoding) ของข้อมูลฟอร์มก่อนส่งไปยังเซิร์ฟเวอร์ แอตทริบิวต์นี้ทำงานเฉพาะเมื่อใช้เมธอด POST เท่านั้น

ค่าที่เป็นไปได้ของ enctype

ค่า (Value) คำอธิบาย
application/x-www-form-urlencoded ค่าเริ่มต้น (Default) เข้ารหัสทุกตัวอักษรก่อนส่ง (ช่องว่างกลายเป็น + ตัวอักษรพิเศษกลายเป็นค่า ASCII HEX)
multipart/form-data ไม่เข้ารหัสตัวอักษร จำเป็นต้องใช้เมื่อฟอร์มมีการอัปโหลดไฟล์ (input type="file")
text/plain ช่องว่างกลายเป็น + แต่ไม่เข้ารหัสตัวอักษรพิเศษ (ใช้ได้น้อย นิยมใช้ในการทดสอบ)

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

ตัวอย่างฟอร์มที่ใช้ enctype="multipart/form-data" สำหรับการอัปโหลดไฟล์:

<!DOCTYPE html>
<html>
<head>
  <title>HTML enctype attribute</title>
  <style>
    form { width: 70%; margin: 0 auto; text-align: center; }
    * { padding: 2px; margin: 5px; }
    input[type="button"] { border-radius: 10px; }
  </style>
</head>
<body>
  <form enctype="multipart/form-data" action="" method="post">
    <fieldset>
      <legend>HTML enctype attribute</legend>
      <label for="EmailSelect">Email: 
        <input type="email" id="EmailSelect">
        <input type="button" onclick="getUserEmail('david')" value="David">
        <input type="button" onclick="getUserEmail('shasha')" value="Shasha"><br>
        <input type="button" onclick="login()" value="Login">
      </label>
      <div id="divDisplay"></div>
    </fieldset>
  </form>
  <script>
    var divDisplay = document.getElementById("divDisplay");
    var inputEmail = document.getElementById("EmailSelect");
    function getUserEmail(userName) {
      if (userName === 'david') inputEmail.value = 'davidMiller@MNC.com';
      else inputEmail.value = 'shashaGreen@MNC.com';
    }
    function login() {
      if (inputEmail.value !== '') divDisplay.textContent = 'Successful Login. Hello ' + inputEmail.value.split("@")[0];
      else divDisplay.textContent = 'Enter Email Id';
    }
  </script>
</body>
</html>

สรุป: เมื่อไหร่ควรใช้ค่าใด?

  • application/x-www-form-urlencoded: ฟอร์มทั่วไป ไม่มีการอัปโหลดไฟล์
  • multipart/form-data: บังคับ เมื่อมี <input type="file">
  • text/plain: นادرใช้ จะข้อมูลอ่านง่าย แต่ไม่ปลอดภัยสำหรับข้อมูลจริง