How to send files to server with Fetch API?

•

Mon Mar 27 2023

•

5 min read

Uploading files to your website or web application can be a challenging task, but with the modern web technologies available today, it doesn't have to be.

The Fetch API provides a fast and efficient way to send and receive data from a server using a simple and intuitive API.

Fetch API

The Fetch API is a modern Web API that allows you to make API requests in JavaScript. It provides a simpler and more flexible alternative to older technologies like AJAX or jQuery for sending and receiving data from a server.

If you want to learn more about Fetch API, you can read our guide here.

Upload Files with HTML form

Before we can start using the Fetch API to upload files, we need to prepare our HTML form to handle file uploads properly.

Creating a basic form for file uploads

To create a basic form for file uploads, we can use the <form> element with the method attribute set to "POST" and the enctype attribute set to "multipart/form-data". This tells the browser that we'll be sending binary data, which is necessary for file uploads.

html
<form action="#" method="POST" enctype="multipart/form-data">
<!-- form fields go here -->
</form>

Adding input fields for file selection

Next, we need to add input fields to our form that allow users to select the files they want to upload. We can use the <input> element with the type attribute set to "file".

html
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<!-- additional form fields go here -->
</form>

Finally, we need to set some additional attributes on our form to ensure that file uploads are handled properly. The "name" attribute on the file input field should match the name of the field in our server-side code that will handle the file upload

html
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" multiple>
<input type="submit" value="Upload">
</form>

Using fetch to send files to server

The basic structure of a Fetch request involves calling the fetch() function with a URL and an options object that specifies the HTTP method, headers, and other request options.

js
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})

To upload files with the Fetch API, we need to create a request body that includes the file data. We can do this using the FormData object, which allows us to append file data to a new FormData instance.

js
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);

In this example, a Fetch request is sent to the /upload endpoint with the POST method and the form data as the request body.

Note that you'll need to replace /upload with the appropriate API endpoint.

Handling the server response

Once the server has finished processing the file upload request, it will send a response back to the client to indicate whether the upload was successful or not. To handle this response on the client side, we can use the Response object that's returned by the fetch() function.

When the response is received, we can use various methods of the response object to retrieve the response data from the server. Here is how:

js
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('File upload failed');
}
})
.then(data => {
console.log('Server response:', data);
})
.catch(error => {
console.error('Error uploading file:', error);
});

Example

Let’s use the File Upload API from the Rapid API hub.

Loading component...

Here’s the entire code that includes a basic form for file uploads and a Fetch request to handle the file upload:

html
<html>
<head>
<title>File Upload with Fetch API</title>
</head>
<body>
<form>
<input type="file" id="fileInput" name="fileInput">
<button type="button" id="uploadButton">Upload</button>
</form>
<script>
const uploadButton = document.getElementById('uploadButton');
const fileInput = document.getElementById('fileInput');
const endpoint = 'https://file-upload8.p.rapidapi.com/upload';
uploadButton.addEventListener('click', () => {
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
fetch(endpoint, {
method: 'POST',
headers: {
'X-RapidAPI-Key': 'your-rapid-key',
'X-RapidAPI-Host': 'file-upload8.p.rapidapi.com'
},
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
alert('File uploaded successfully!');
})
.catch(error => {
console.error(error);
alert('Error uploading file');
});
});
</script>
</body>
</html>

Error handling with file uploads

When uploading files using the Fetch API, there are several common errors that can occur. These include network errors, server errors, and user errors, such as selecting an invalid file type or a file that exceeds the maximum file size allowed.

To handle these errors, we can use the try-catch block if we are using async/await with fetch. Here is how we can do it:

js
try {
const formData = new FormData();
formData.append('fileToUpload', fileInput.files[0]);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
if (response.ok) {
const data = await response.json();
console.log('Server response:', data);
} else {
throw new Error('File upload failed');
}
} catch (error) {
console.error('Error uploading file:', error);
}

The code is wrapped in a try...catch block, which is used to catch any errors that may occur during the file upload or fetch request. If an error is caught, it will be logged to the console using console.error().

If the status code indicates success, the response is parsed using the json() method, and the parsed data is logged to the console using console.log(). If the status code indicates failure, an error is thrown using throw new Error().

Wrap Up

The Fetch API provides an efficient way to handle file uploads in web applications. With a few lines of code, you can create an HTML form for file uploads, use the Fetch API to make the request to the server and handle the response data.