Uploading files from the client side to a server is a common requirement in web applications. This article will guide you through the steps to upload files using the fetch
API in JavaScript. We’ll cover the basics of the fetch
API, setting up a server endpoint to receive the files, and the client-side code to handle and send the file data.
Understanding the Fetch API
The fetch
API is used to make HTTP requests in JavaScript. It's a modern alternative to the older XMLHttpRequest
and works in almost all modern browsers. The API is simple and uses Promises, making asynchronous code more manageable.
fetch('https://example.com/api/upload', {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Setting Up the Server
For the server part, you need an endpoint to handle file uploads. Let's assume we're using Node.js with the Express framework and the multer
middleware to handle file uploads:
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
if (req.file) {
res.json({
success: true,
fileName: req.file.filename,
});
} else {
res.status(400).json({
success: false,
message: 'File upload failed'
});
}
});
app.listen(3000, () => console.log('Server started on port 3000'));
In this setup, we define an endpoint /upload that handles POST requests. We use multer
to process multipart/form-data
file uploads.
Creating the HTML Form
Before we upload a file, let's create a simple HTML form that allows users to select a file:
<form id="upload-form">
<input type="file" id="file-input" name="file" />
<button type="button" onclick="uploadFile()">Upload</button>
</form>
Client-Side JavaScript Code
Now it's time to write the client-side JavaScript code using the fetch
API:
function uploadFile() {
const form = document.getElementById('upload-form');
const formData = new FormData(form);
fetch('http://localhost:3000/upload', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
}
In this code, we create a new FormData
object from our form, which automatically encodes it into the correct multipart/form-data
format required for file uploads. The fetch
function sends a POST request to our server with the file data.
Testing the Upload
With the server running on port 3000 and both the server and client code set, try selecting a file with the form and clicking the "Upload" button. Upon successfully uploading the file, the server should respond with a success message, which you'll see in the console.
This tutorial demonstrates the straightforward use of the fetch
API to upload files from the browser to the server in a modern web application. With only a few lines of both server-side and client-side code, you can efficiently implement file upload functionality.