JS : วิธีตั้งค่าจำกัดขนาดของรูปภาพ
ภารกิจ
Set the maximum size of the uploaded image (Max size: 10MB)
สารละลาย
ขั้นตอนที่ 1.
กำหนดกล่องอินพุตที่มีประเภท "ไฟล์" และเรียกใช้ฟังก์ชัน onChange (profileImageHandler)
<input id="profileInput" name="profileImage" type="file" hidden onChange={(e) => profileImageHandler(e)} />
ขั้นตอนที่ 2.
กำหนดวิธีการทำงานของ profileImageHandler
ใส่ตรรกะในการจำกัดขนาดสูงสุดของไฟล์ภาพไว้ที่นี่
const profileImageHandler = (e) => { const file = e.target.files[0]; //If statement here can limit the size of image file up to 10mb. if (file && file.size > 10 * 1024 * 1024) { alert("파일 사이즈가 10mb 를 넘습니다."); e.target.value = null; return; // stop the function if the file is too large } if (file) { setProfile(URL.createObjectURL(file)); } };
++ วิธีตรวจสอบค่าของ formData โดยใช้ console.log
- ต่อไปนี้เป็นวิธีตรวจสอบค่าของ formData โดยใช้ console.log ไม่เหมือนกับที่เราใช้ console.log ในกรณีปกติ
for (let value of formData.values()) { console.log("value", value); }