Home >Web Front-end >JS Tutorial >How Can I Upload Files Using the JavaScript Fetch API?
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!