Ajax

出自六年制學程
在2022年6月26日 (日) 10:46由丁志仁對話 | 貢獻所做的修訂版本

跳轉到: 導覽搜尋

HTTP 中的 form-data Content-Type

常見的傳輸格式:

  1. Content-Type: application/json 代表請求內容是 JSON
  2. Content-Type: image/png 代表請求內容是圖片檔
  3. Content-Type: multipart/form-data 使用 (RFC7578) 規範,用一個請求傳送複數個資料格式,主要用於表單或實作檔案上傳

FormData 類別

資料後送

etable 舊版

檔案上傳

前台程式

<!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'; 
}

?>