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

How Can I Upload Files Using the JavaScript Fetch API?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 02:16:12872browse

How Can I Upload Files Using the JavaScript Fetch API?

Uploading Files Using the JS Fetch API: Unveiling the Secrets

Understanding how to upload files with the JS fetch API can be a daunting task. To clarify this concept, we will break down how to send a file for uploading upon capturing the submit event.

Firstly, remember that the input tag allows us to select a file (or even multiple) using the file input method. To catch the submit event, you'll need to specify the appropriate event handler in your code.

Now comes the crucial part: sending the file using fetch. The syntax for this is:

fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);

To successfully send a file, we need to populate the body property with the file data and set the correct Content-Type header. Here's an enhanced code snippet that demonstrates how to do this:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

In this code, FormData is used to create a new form data object, and the file data is appended using the append method. The Content-Type header is automatically set to multipart/form-data, which is required for file upload requests.

With this in place, your code can effortlessly upload files to a server using the fetch API.

The above is the detailed content of How Can I Upload Files 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