如何在 HTML 中新增檔案上傳功能到網頁?
簡介
在本文中,我們將引導您完成將檔案上傳功能新增到網頁的過程。我們將向您展示如何建立一個帶有檔案輸入欄位的 HTML 表單,以及如何建立一個處理檔案上傳過程的指令碼。
方法
我們可以在 HTML 中使用兩種方法將檔案上傳功能新增到網頁,如下所示:
使用帶有檔案輸入欄位的基本 HTML 表單
使用 jQuery 和 ajax
現在讓我們詳細討論一下。
方法 1:使用帶有檔案輸入欄位的基本 HTML 表單
此方法涉及建立一個簡單的 HTML 表單,其中包含一個檔案輸入欄位,允許使用者選擇要上傳的檔案。然後將表單傳送到處理實際檔案儲存的伺服器端指令碼。
步驟 1 - 建立一個名為 index.html 的檔案。
步驟 2 - 建立一個帶有檔案輸入欄位的 HTML 表單。
示例
讓我們透過一個例子更好地理解這一點。
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>Welcome to Tutorials Point</h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedFile">
<input type="submit" value="Upload">
</form>
</body>
</html>
這將建立一個帶有檔案輸入欄位的 HTML 表單,允許使用者選擇要上傳的檔案,以及一個提交按鈕來發送表單。action 屬性設定為 "upload.php",這是將處理檔案上傳的伺服器端指令碼。enctype 屬性設定為 "multipart/form-data",這對於檔案上傳是必需的。
步驟 3 - 建立伺服器端 PHP 指令碼 (action.php) 來處理檔案上傳。
<?php
if(isset($_FILES['uploadedFile'])){
$errors= array();
$file_name = $_FILES['uploadedFile']['name'];
$file_size = $_FILES['uploadedFile']['size'];
$file_tmp = $_FILES['uploadedFile']['tmp_name'];
$file_type = $_FILES['uploadedFile']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"upload/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
此指令碼首先使用 isset 函式和 $_FILES 超全域性變數檢查檔案輸入欄位是否包含檔案。然後,指令碼使用 in_array 函式和預定義的允許副檔名列表檢查檔案大小和副檔名。如果檔案有效,則使用 move_uploaded_file 函式將其移動到伺服器上的 "upload" 目錄。如果檔案無效,則顯示錯誤訊息。
方法 2:使用 jQuery 和 ajax
此方法是處理檔案上傳的更高階方法,允許您處理檔案上傳過程,而無需重新整理頁面。
步驟 1 - 建立一個名為 index.html 的檔案
步驟 2 - 在此檔案中包含 jQuery 和 jQuery Form 外掛 -
示例
讓我們透過一個例子更好地理解這一點。
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://malsup.github.io/jquery.form.js"></script>
此步驟涉及在您的 HTML 文件中包含 jQuery 和 jQuery Form 外掛庫。這些庫將允許您使用 ajaxForm 方法透過 JavaScript 處理檔案上傳過程。
步驟 3 − 建立一個帶有檔案輸入欄位的 HTML 表單 -
<form id="fileUploadForm" action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploadedFile"> <input type="submit" value="Upload"> </form>
此步驟類似於方法 1 的步驟 1。您建立一個帶有檔案輸入欄位和提交按鈕的 HTML 表單,並將 action 屬性設定為指向將處理檔案上傳的伺服器端指令碼,並將 enctype 屬性設定為 "multipart/form-data",因為這對於檔案上傳是必需的。
步驟 4 - 使用 jQuery 處理檔案上傳 -
$(document).ready(function(){
$('#fileUploadForm').ajaxForm({
beforeSubmit: function(){
// do validation here
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var maxFileSize = 2097152; // 2 MB
var validFileExtensions = ["jpg", "jpeg", "png"];
var extension = file.name.split('.').pop().toLowerCase();
if(file.size > maxFileSize) {
alert("File size must be exactly 2 MB.");
return false;
}
if(validFileExtensions.indexOf(extension) === -1) {
alert("Invalid file type. Only JPEG and PNG files are allowed.");
return false;
}
},
success: function(response){
// handle response
var jsonResponse = JSON.parse(response);
if(jsonResponse.status === "success"){
alert("File upload successful!");
}else{
alert("File upload failed. Please try again.");
}
},
error: function(response){
// handle errors
alert("There was an error while uploading the file. Please try again later.");
}
});
});
此步驟涉及使用 jQuery 處理檔案上傳過程。ajaxForm 方法用於透過 JavaScript 提交表單,beforeSubmit、success 和 error 函式用於處理檔案上傳過程的各個階段。
beforeSubmit 函式用於在上傳之前驗證檔案,success 函式用於處理檔案上傳後伺服器的響應。error 函式用於處理檔案上傳過程中發生的任何錯誤。
步驟 5 - index.html 檔案的 jQuery 程式碼的完整 HTML 如下所示:
示例
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://malsup.github.io/jquery.form.js"></script>
</head>
<body>
<h1>Greetings from Tutorials Point!</h1>
<form id="fileUploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedFile">
<input type="submit" value="Upload">
</form>
<script>
$(document).ready(function(){
$('#fileUploadForm').ajaxForm({
beforeSubmit: function(){
// do validation here
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var maxFileSize = 2097152; // 2 MB
var validFileExtensions = ["jpg", "jpeg", "png"];
var extension = file.name.split('.').pop().toLowerCase();
if(file.size > maxFileSize) {
alert("File size must be exactly 2 MB.");
return false;
}
if(validFileExtensions.indexOf(extension) === -1) {
alert("Invalid file type. Only JPEG and PNG files are allowed.");
return false;
}
},
success: function(response){
// handle response
var jsonResponse = JSON.parse(response);
if(jsonResponse.status === "success"){
alert("File upload successful!");
}else{
alert("File upload failed. Please try again.");
}
},
error: function(response){
// handle errors
alert("There was an error while uploading the file. Please try again later.");
}
});
});
</script>
</body>
</html>
步驟 6 - 建立 PHP 伺服器端指令碼 (upload.php) 來處理檔案上傳 -
<?php
if(isset($_FILES['uploadedFile'])){
$errors= array();
$file_name = $_FILES['uploadedFile']['name'];
$file_size = $_FILES['uploadedFile']['size'];
$file_tmp = $_FILES['uploadedFile']['tmp_name'];
$file_type = $_FILES['uploadedFile']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"upload/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
此指令碼首先使用 isset 函式和 $_FILES 超全域性變數檢查檔案輸入欄位是否包含檔案。然後,指令碼使用 in_array 函式和預定義的允許副檔名列表檢查檔案大小和副檔名。如果檔案有效,則使用 move_uploaded_file 將其移動到伺服器上的 "upload" 目錄。
結論
在本文中,我們討論了兩種在 HTML 中將檔案上傳功能新增到網頁的方法。第一種方法是使用帶有檔案輸入欄位的基本 HTML 表單,然後將表單傳送到處理實際檔案儲存的伺服器端指令碼。第二種方法是使用 jQuery 和 ajax,此方法允許您處理檔案上傳過程,而無需重新整理頁面。
這兩種方法都需要適當的驗證、適當的檔案儲存方式、伺服器端正確的許可權,以及出於安全原因對檔名和副檔名的適當清理方式。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP