Ajax 简明教程

Fetch API - Uploading Files

Fetch API 提供了一种灵活的方法来创建 HTTP 请求,该请求将文件上传到服务器。我们可以将`fetch()`函数与`FormData`对象一起使用,以在请求中发送单个或多个文件。让我们在以下示例的帮助下讨论这个概念:

Example − Uploading a Single File

在以下程序中,我们一次使用 fetch API 上传一个文件。此处我们使用`FormData`对象存储文件,然后使用`fetch()`函数将其发送到给定的 URL,其中包括 POST 请求方法和`FormData`对象。在向服务器发送请求后,我们现在使用`then()`函数来处理响应。如果我们遇到一个错误,则该错误由`catch()`函数处理。

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

      // Send the file to the given URL
      fetch("https://httpbin.org/post", {
         // POST request with Fetch API
         method: "POST",

         // Adding FormData to the request
         body: myData
      })
      // Converting the response in JSON
      // using response.json() function
      .then(response => response.json())
      .then(finalData => {
         // Handling the response
         console.log("File has been uploaded successfully");
      })
      .catch(err=>{
         // Handling the error
         console.log("Error Found:", err)
      });
   })
</script>
</body>
</html>

Output

uploading files

Example − Uploading Multiple Files for Single Input

在以下程序中,我们将使用 fetch API 从单个输入中上传多个文件。此处我们在`<input>`标签中添加一个“multiple”属性以添加多个文件。然后我们使用`FormData`对象存储多个文件,然后使用`fetch()`函数将其发送到给定的 URL,其中包括 POST 请求方法和`FormData`对象。在向服务器发送请求后,我们现在使用`then()`函数来处理响应。如果我们遇到一个错误,则该错误由`catch()`函数处理。

<!DOCTYPE html>
<html>
<body>
   <!-- Creating a form to upload a file-->
   <h2> Uploading Multiple files</h2>
   <form id = "myForm">
      <p>Maximum number of files should be 2</p>
      <input type="file" id="file" multiple><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 multiple files 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);

      // Send the file to the given URL
      fetch("https://httpbin.org/post", {
         // POST request with Fetch API
         method: "POST",

         // Adding FormData to the request
         body: myData
      })
      // Converting the response in JSON
      // using response.json() function
      .then(response => response.json())
      .then(finalData => {
         // Handling the response
         console.log("Files has been uploaded successfully");
      })
      .catch(err=>{
         // Handling the error
         console.log("Error Found:", err)
      });
   })
</script>
</body>
</html>

Output

uploading files2

Example − Uploading Multiple Files

在以下程序中,我们将使用 fetch API 上传多个文件。此处我们从具有文件类型属性的 DOM 中从系统中选择两个文件。然后我们将输入文件添加到数组中。然后我们创建一个`FormData`对象并将输入文件追加到该对象。然后我们使用`fetch()`函数将其发送到给定的 URL,其中包括 POST 请求方法和`FormData`对象。在向服务器发送请求后,我们现在使用`then()`函数来处理响应。如果我们遇到一个错误,则该错误由`catch()`函数处理。

<!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);
      }
      // Upload the FormData object
      fetch('https://httpbin.org/post', {
         method: "POST",
         body: myformdata,
      })
      // Handle the response
      .then(response => response.json())
      .then(response => console.log(response))

      // Handle the error
      .catch(err => console.log("Error Found:", err))
   })
</script>
</body>
</html>

Output

uploading files3

Conclusion

因此,这就是我们如何在`fetch()`API 的帮助下将文件上传到给定 URL 的方式。此处我们可以上传任何类型的文件,如 jpg、pdf、word 等,并且可以一次上传任何数量的文件,如一次一个文件或一次多个文件。现在在下一篇文章中,我们将学习 Fetch API 如何处理响应。