Home > Web Front-end > JS Tutorial > How to Send Files to a Server Using the JavaScript Fetch API?

How to Send Files to a Server Using the JavaScript Fetch API?

Mary-Kate Olsen
Release: 2024-11-30 09:05:11
Original
219 people have browsed it

How to Send Files to a Server Using the JavaScript Fetch API?

How to Upload a File Using JS Fetch API

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">
Copy after login

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?
})
Copy after login

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]);
Copy after login

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');
Copy after login

With the FormData object ready, we can finally construct the fetch request as follows:

fetch('/avatars', {
  method: 'POST',
  body: formData
})
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template