Ajax 简明教程

AJAX - File Uploading

AJAX 提供了一种创建可将文件上传到服务器的 HTTP 请求的灵活方法。我们可以使用 FormData 对象在请求中发送单个或多个文件。让我们借助以下示例来讨论此概念 −

AJAX provides a flexible way to create an HTTP request which will upload files to the server. We can use the FormData object to send single or multiple files in the request. Let us discuss this concept with the help of the following examples −

Example − Uploading a Single File

在以下示例中,我们将使用 XMLHttpRequest 上传单个文件。因此,首先我们创建一个简单的表单,其中包含一个文件上传按钮和一个提交按钮。现在,我们在 JavaScript 中编写代码,在其中我们获取表单元素并在单击上传文件按钮时创建触发器的事件。在此事件中,我们将上传的文件添加到 FormData 对象中,然后创建一个 XMLHttpRequest 对象,该对象将使用 FormData 对象将文件发送到服务器,并处理服务器返回的响应。

In the following example, we will upload a single file using XMLHttpRequest. So for that first we create a simple form which has a file upload button and the submit button. Now we write JavaScript in which we get the form element and create an event which triggers when we click on the upload file button. In this event, we add the uploaded file to the FormData object and then create an XMLHttpRequest object which will send the file using the FormData object to the server and handle the response returned by the server.

<!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>

Output

fileupload

Example − Uploading Multiple Files

在以下示例中,我们将使用 XMLHttpRequest 上传多个文件。这里我们在 DOM 中从具有文件类型属性的系统中选择两个文件。然后我们将输入文件添加到一个数组中。然后我们创建一个 FormData 对象并将输入文件附加到该对象。然后我们创建一个 XMLHttpRequest 对象,该对象将使用 FormData 对象将文件发送到服务器,并处理服务器返回的响应。

In the following example, we will upload multiple files using XMLHttpRequest. Here we select two files from the system in DOM with the attribute of file type. Then we add the input files in an array. Then we create a FormData object and append the input files to the object. Then we create an XMLHttpRequest object which will send the files using the FormData object to the server and handle the response returned by the server.

<!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>

Output

fileupload2

Conclusion

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

So this is how we can upload files to the given URL with the help of XMLHttpRequest. Here we can upload any type of file such as jpg, pdf, word, etc and can upload any number of files like one file at a time or multiple files at a time. Now in the next article, we will learn how to create a FormData object using XMLHttpRequest.