<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload Form</title>
</head>
<body>
<h2>Upload File</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="file">Select a file:</label>
<input type="file" id="file" name="file" accept=".txt, .pdf, .doc, .docx">
<br><br>
<button type="submit">Upload</button>
</form>
</body>
</html>
注意:當一個表單包含<input type="file">
時,表單的enctype
必須指定為multipart/form-data
,method
必須指定為post
,瀏覽器才能正確編碼並以multipart/form-data
格式傳送表單的資料。
HTML5的File API
File
物件用於獲取檔案的基本資訊,而 FileReader
物件則用於讀取檔案內容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File API Example</title>
</head>
<body>
<h2>選擇檔案並讀取內容</h2>
<input type="file" id="fileInput">
<div id="fileInfo"></div>
<hr>
<div id="fileContent"></div>
<script>
function handleFileSelect(event) {
var file = event.target.files[0]; // 獲取第一個檔案
// 顯示檔案資訊
var fileInfo = document.getElementById('fileInfo');
fileInfo.innerHTML = '<strong>檔案資訊:</strong> ' + file.name + ', 型別: ' + file.type + ', 大小: ' + file.size + ' 位元組';
// 使用FileReader讀取檔案內容
var reader = new FileReader();
reader.onload = function (event) {
var contents = event.target.result;
var fileContent = document.getElementById('fileContent');
fileContent.textContent = contents;
};
// 讀取檔案內容
reader.readAsText(file);
}
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>