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

How Can I Upload Files to a Server Using the JavaScript Fetch API?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 05:34:13656browse

How Can I Upload Files to a Server Using the JavaScript Fetch API?

File Uploading with JS Fetch API

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!

Statement:
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