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 中的系统中选择两个属性为 file 的文件。然后我们将输入文件添加到数组中。然后我们创建一个 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 如何处理响应。