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>

输出

文件上传

示例 − 上传多个文件

在下面的示例中,我们将使用 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>

输出

文件上传 2

结论

这就是我们如何借助 XMLHttpRequest 将文件上传到给定的 URL。 在这里我们可以上传任何类型的文件,例如jpg、pdf、word等,并且可以上传任意数量的文件,例如一次一个文件或一次多个文件。 在下一篇文章中,我们将学习如何使用 XMLHttpRequest 创建 FormData 对象。