获取 API - 上传文件

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

示例 − 上传单个文件

在下面的程序中,我们使用 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>

输出

上传文件

示例 − 为单个输入上传多个文件

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

输出

上传文件

示例 − 上传多个文件

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

输出

上传文件

结论

这就是我们如何借助 fetch() API 将文件上传到给定的 URL。 在这里,我们可以上传任何类型的文件,如 jpg、pdf、word 等,也可以上传任意数量的文件,如一次一个文件或一次多个文件。 在下一篇文章中,我们将了解 Fetch API 如何处理响应。