Tag Archive browse

Byphunsanit

เลือกชนิดไฟล์อัพโหลด

คุณสมบัติที่น่าสนใจอย่างหนึ่งของ HTML 5 คือเราสามารถกำหนดให้อินพุทยอมรับชนิดไฟล์ตามที่เราต้องการได้ ช่องใส่ภาพประจำตัว ก็น่าจะใส่ได้แค่นามสกุล jpeg อย่างน้อยก็ png หรือ gif แต่ก็มียูเซอร์ copy รูปใส่ word upload เข้ามา สมกับ used เซ่อๆ จริงๆ
เราสามารถกำหนดได้โดยใช้ accept Attribute ตามตัวอย่าง

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Form Input Accept</title>
<style>
label
{
	display: block;
}
</style>
</head>
<body>
<form action="" enctype="multipart/form-data">
	<label>เฉพาะไฟล์เสียง
		<input type="file" name="files[]" accept="audio/*">
	</label>
	<label>เฉพาะรูปภาพ
		<input type="file" name="files[]" accept="image/*">
	</label>
	<label>เฉพาะวีดีโอ
		<input type="file" name="files[]" accept="video/*">
	</label>
	<label>pdf
		<input type="file" name="files[]" accept="application/pdf">
	</label>
	<label>.gif หรือ .png
		<input type="file" name="files[]" accept="image/gif, image/png">
	</label>
	<label>.jpg
		<input type="file" name="files[]" accept="image/pjpeg, image/jpeg">
	</label>
	<input type="submit">
</form>
</body>
</html>

จะสังเกตุว่าเวลาเรา browse file มันจะแสดงเฉพาะนามสกุลที่เรากำหนด แต่ยังเปลี่ยนตัวเลือกไปเป็น All Files (*.*) ได้อยู่ดี มันแค่ช่วยให้เลือกไฟล์ได้ง่ายขึ้น ยังรับประกันไม่ได้อยู่ดีว่าจะได้นามสกุลไฟล์ที่ถูกต้อง หรือไฟล์ที่ส่งมานามสกุลถูกตาม Extension แต่ก็ไม่ได้รับรองว่าไฟล์มันเป็นจริงตามนามสกุลที่ส่งมา จุดที่อันตรายก็เลยต้องมาตรวจชนิดไฟล์ในผั่ง server อยู่เหมือนเดิม

ค่าที่ใส่ใน accept คือ MIME Types ดูเพิ่มเติมได้ที่ The Complete List of MIME Types