Ajax

出自六年制學程
於 2022年6月24日 (五) 15:37 由 丁志仁留言 | 貢獻 所做的修訂 (新頁面: ==檔案上傳== ===前台程式=== <pre><!DOCTYPE html> <html> <head> <title> Ajax JavaScript File Upload Example </title> </head> <body> <!-- HTML5 Input Form Elements --...)
(差異) ←上個修訂 | 最新修訂 (差異) | 下個修訂→ (差異)
跳至導覽 跳至搜尋

檔案上傳

前台程式

<!DOCTYPE html> 
<html> 
 <head> 
  <title> Ajax JavaScript File Upload Example </title> 
 </head> 
 <body>
  <!-- HTML5 Input Form Elements -->
  <input id="fileupload" type="file" name="formData" /> 
  <button id="upload-button" onclick="uploadFile()"> Upload </button>

  <!-- Ajax JavaScript File Upload Logic -->
  <script>
  async function uploadFile() {
  let formData = new FormData(); 
  formData.append("file", fileupload.files[0]);
  await fetch('./upload.php', {
    method: "POST", 
    body: formData
  }); 
  alert('The file has been uploaded successfully.');
  }
  </script>

 </body> 
</html>

對應的後台程式 upload.php

<?php

/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];

/* Choose where to save the uploaded file */
$location = "./upload/".$filename;

/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) { 
  echo 'Success'; 
} else { 
  echo 'Failure'; 
}

?>