<input type="file">
的用法。表單與檔案上傳
<form>
是用來收集使用者輸入的結構。<input type="file">
可以讓使用者從電腦或手機選擇檔案。accept="image/*"
可以限制只能選擇圖片格式(例如 JPG、PNG)。JavaScript 檔案讀取
FileReader
API 來讀取使用者上傳的檔案。readAsDataURL(file)
可以把圖片轉換成「Base64 編碼」,讓它可以直接顯示在 <img>
裡。onload
事件:當圖片讀取完成後,就把結果放進 img.src
顯示出來。應用場景
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>Day 5 - 圖片上傳</title>
<style>
body {
font-family: "Microsoft JhengHei", Arial, sans-serif;
background-color: #f9f9f9;
margin: 20px;
}
h1 {
text-align: center;
color: #4aa3df;
}
.upload-box {
text-align: center;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
max-width: 500px;
margin: 0 auto;
}
input[type="file"] {
margin: 15px 0;
}
img {
max-width: 100%;
margin-top: 15px;
border-radius: 10px;
border: 2px solid #ddd;
}
</style>
</head>
<body>
<h1>🌟 我的第五天網頁 🌟</h1>
<div class="upload-box">
<h2>圖片上傳與預覽</h2>
<p>請選擇一張圖片,系統會即時顯示:</p>
<!-- 圖片上傳 -->
<input type="file" id="upload" accept="image/*">
<!-- 圖片預覽 -->
<div>
<img id="preview" src="" alt="預覽區" style="display:none;">
</div>
</div>
<script>
const upload = document.getElementById("upload");
const preview = document.getElementById("preview");
upload.addEventListener("change", function() {
const file = this.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
preview.src = e.target.result;
preview.style.display = "block";
}
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
<input type="file">
的用法,可以建立圖片上傳表單。FileReader
來讀取並顯示圖片。