Uploading files using the JS fetch API can be perplexing initially. After selecting the file(s) using a file input, the next step is to integrate the fetch() method to send the file to the server.
To utilize the fetch API for file uploading, you'll need to construct a FormData object. This object encapsulates both the file data and any additional form data you wish to include.
var input = document.querySelector('input[type="file"]'); var data = new FormData(); data.append('file', input.files[0]); // Append the selected file to the form data
In addition to the file, you can add other data to the form using append(), as exemplified in the code below:
data.append('user', 'hubot'); // Append additional form data
Now, you can use the fetch() method to make a POST request to your server endpoint, passing the form data as the request body:
fetch('/avatars', { method: 'POST', body: data }).then(function(response) { // Handle the response from the server });
This approach enables you to send files and other data conveniently using the fetch API's sophisticated features.
The above is the detailed content of How Can I Upload Files to a Server Using the JavaScript Fetch API?. For more information, please follow other related articles on the PHP Chinese website!