Uploading a file via the fetch API is a valuable technique for transmitting data from a web application to a server. As a developer, it's essential to understand the process to handle file uploads effectively.
Consider the scenario where you have an input field that allows users to select a file:
<input type="file">
Upon submission of the form containing the file input, you need to employ fetch() to transmit the file to the server. However, this task requires careful attention to the request body's structure.
fetch('/files', { method: 'POST', // What goes here? How do we construct the body? })
To construct the body of the request, we leverage the FormData interface. This interface enables the creation of a collection of key-value pairs that can include file objects.
const formData = new FormData(); formData.append('file', input.files[0]);
In the above code, we append the selected file to the FormData object using the append method. The first argument represents the key, while the second argument is the file object retrieved from the file input.
Additionally, you may include other key-value pairs in the FormData object if necessary. For instance, you could add user data:
formData.append('user', 'hubot');
With the FormData object ready, we can finally construct the fetch request as follows:
fetch('/avatars', { method: 'POST', body: formData })
This request will send the selected file and any additional data in the FormData object to the '/avatars' endpoint on the server. The server can then process the file as needed.
The above is the detailed content of How to Send Files to a Server Using the JavaScript Fetch API?. For more information, please follow other related articles on the PHP Chinese website!