แก้ปัญหาภาพไม่แสดงเมื่อใช้ AI เขียนโค้ดให้ดึงรูปภาพจาก google drive มาแสดงหน้าเว็ป คือบางครั้ง URL จาก Google Drive ที่ AI เขียนให้ อาจมีหลายรูปแบบ เช่น
https://drive.google.com/open?id=FILE_ID https://drive.google.com/uc?id=FILE_ID https://drive.google.com/file/d/FILE_ID/view
แนะนำให้ดึง FILE_ID แบบปลอดภัยโดยใช้ RegEx ไม่ว่า URL จะมีรูปแบบใด
ตัวอย่าง:
function getDriveFileId(url) {
return (
url.match(/\/d\/([a-zA-Z0-9_-]+)/)?.[1] ||
url.match(/id=([a-zA-Z0-9_-]+)/)?.[1] ||
''
);
}
ตัวอย่าง:เรียกใช้: (javascript)
const fileId = getDriveFileId(url);
const imageUrl = `https://lh3.googleusercontent.com/d/${fileId}`;
<img src="https://lh3.googleusercontent.com/d/${fileId}">
หรือ<img src="${imageUrl}">
หรือใช้แบบนี้: (javascript)
${ row['รูปภาพ']
? `<img src="https://lh3.googleusercontent.com/d/${getDriveFileId(row['รูปภาพ'])}">`
: `<div style="display:flex;align-items:center;justify-content:center;font-size:12pt;color:#999;">
ติดรูปถ่าย<br>1.5 นิ้ว
</div>`
}
**** row['รูปภาพ'] คือ ตัวแปรที่เก็บ URL รูปภาพ จาก Google Drive