AJAX - 檔案上傳



AJAX 提供了一種靈活的方式來建立 HTTP 請求,該請求將檔案上傳到伺服器。我們可以使用 FormData 物件在請求中傳送單個或多個檔案。讓我們透過以下示例來討論這個概念:

示例 - 上傳單個檔案

在下面的示例中,我們將使用 XMLHttpRequest 上傳單個檔案。為此,我們首先建立一個簡單的表單,其中包含一個檔案上傳按鈕和一個提交按鈕。現在,我們編寫 JavaScript 程式碼,在其中獲取表單元素並建立一個在點選上傳檔案按鈕時觸發的事件。在這個事件中,我們將上傳的檔案新增到 FormData 物件中,然後建立一個 XMLHttpRequest 物件,該物件將使用 FormData 物件將檔案傳送到伺服器並處理伺服器返回的響應。

<!DOCTYPE html>
<html>
<body>
<!-- Creating a form to upload a file-->  
<form id = "myForm">
   <input type="file" id="file"><br><br>
   <button type="submit">Upload File</button>
</form>
<script>
   document.getElementById('myForm').addEventListener('submit', function(x){
      // Prevent from page refreshing
      x.preventDefault();
   
      // Select the file from the system
      // Here we are going to upload one file at a time
      const myFile = document.getElementById('file').files[0];
   
      // Create a FormData to store the file
      const myData = new FormData();
      // Add file in the FormData
      myData.append("newFiles", myFile);
   
      // Creating XMLHttpRequest object
      var myhttp = new XMLHttpRequest();
   
      // Callback function to handle the response
      myhttp.onreadystatechange = function(){
         if (myhttp.readyState == 4 && myhttp.status == 200) {
            console.log("File uploaded Successfully")
         }
      };
   
      // Open the connection with the web server
      myhttp.open("POST", "https://httpbin.org/post", true);
   
      // Setting headers
      myhttp.setRequestHeader("Content-Type", "multipart/form-data");
   
      // Sending file to the server
      myhttp.send(myData);
   })
</script>
</body>
</html>

輸出

File Upload

示例 - 上傳多個檔案

在下面的示例中,我們將使用 XMLHttpRequest 上傳多個檔案。在這裡,我們使用檔案型別的屬性在 DOM 中選擇系統中的兩個檔案。然後我們將輸入檔案新增到陣列中。然後我們建立一個 FormData 物件並將輸入檔案新增到該物件。然後我們建立一個 XMLHttpRequest 物件,該物件將使用 FormData 物件將檔案傳送到伺服器並處理伺服器返回的響應。

<!DOCTYPE html>
<html>
<body>
<!-- Creating a form to upload multiple files-->  
<h2> Uploading Multiple files</h2>  
<input type="file">
<input type="file">
<button>Submit</button>
<script>
   const myButton = document.querySelector('button');
   myButton.addEventListener('click', () => {
      // Get all the input files in DOM with attribute type "file":
      const inputFiles = document.querySelectorAll('input[type="file"]');
   
      // Add input files in the array 
      const myfiles = [];
      inputFiles.forEach((inputFiles) => myfiles.push(inputFiles.files[0]));
   
      // Creating a FormData
      const myformdata = new FormData();
   
      // Append files in the FormData object
      for (const [index, file] of myfiles.entries()){
         // It contained reference name, file, set file name
         myformdata.append(`file${index}`, file, file.name);
      }
      // Creating an XMLHttpRequest object
      var myhttp = new XMLHttpRequest();
   
      // Callback function
      // To handle the response
      myhttp.onreadystatechange = function(){
         if (myhttp.readyState == 4 && myhttp.status == 200) {
            console.log("File uploaded Successfully")
         }
      };
      // Open the connection with the web server
      myhttp.open("POST", "https://httpbin.org/post", true);
   
      // Setting headers
      myhttp.setRequestHeader("Content-Type", "multipart/form-data");
   
      // Sending file to the server
      myhttp.send(myformdata);
   })
</script>
</body>
</html>

輸出

File Upload 2

結論

這就是我們如何使用 XMLHttpRequest 將檔案上傳到給定 URL 的方法。在這裡,我們可以上傳任何型別的檔案,例如 jpg、pdf、word 等,並且可以一次上傳一個檔案或多個檔案。在下一篇文章中,我們將學習如何使用 XMLHttpRequest 建立 FormData 物件。

廣告
© . All rights reserved.