Building a File Upload API in Express
Creating a file upload API is a common requirement for web applications that handle user-submitted documents, images, or other media files. In this article, we'll guide you through building a secure and efficient file upload API using Express and Multer. You'll learn how to set up your project, handle incoming files, and store them securely, ensuring your application reliably manages user-uploaded content.
Prerequisites
- Node.js
Setup project
Setting up the Node.js project dependencies.
npm install express multer
Project structure
├─ index.js
└─ public
└─ index.html
Project files
index.js
This file acts as the main entry point for the Express application, handling the creation and configuration of the Express server. Since the API only has a single route for form submission, both the route and its handler function are defined within this file.
const express = require('express')
const multer = require('multer')
let app = express()
app.use(express.json(), express.static('public'))
let upload = (field) => {
return multer({
storage: multer.diskStorage({
destination: './public/uploads/',
filename: (req, file, cb) => {
cb(null, file.originalname)
}
})
}).single(field)
}
app.post('/submit', upload('image'), (req, res) => {
res.send({
name: req.body.name,
image: req.file.filename
})
})
app.listen(8000)
This Express API handles file uploads using the Multer middleware. Here’s a summary of its functionality:
- Sets up the Express server to serves static files from the public directory and listens for incoming requests on port 8000.
- Configures Multer to store uploaded files in the
./public/uploads/
directory with their original names. - Defines a reusable
upload
function that sets up Multer with disk storage and a custom filename for uploaded files. - Implements a POST route at
`/submit`
which uses theupload
function to handle file uploads. - Responds with a JSON object containing the submitted name and the filename of the uploaded image.
index.html
This HTML form is designed for users to upload a product name along with an associated image file.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
<script>
function submitForm() {
let form = document.getElementById('form')
let data = new FormData(form)
fetch('submit', {
method: 'POST',
body: data
}).then(res => {
res.json().then(result => {
let alert = document.getElementById('alert')
alert.children[0].innerText = `Upload success!\nName: ${result.name}\nImage: ${result.image}`
alert.children[1].src = `/uploads/${result.image}`
alert.classList.remove('d-none')
form.reset()
})
})
return false
}
</script>
</head>
<body>
<div class="container">
<div class="row mt-3">
<form id="form" onsubmit="return submitForm()">
<div class="mb-3 col-12">
<label class="form-label" for="name">Name</label>
<input id="name" name="name" class="form-control form-control-sm" required />
</div>
<div class="mb-3 col-12">
<label class="form-label" for="image">Image</label>
<input type="file" accept="image/*" id="image" name="image" class="form-control form-control-sm" required />
</div>
</div>
<div class="col-12">
<button class="btn btn-sm btn-primary">Submit</button>
</div>
</form>
<div id="alert" class="alert alert-success mt-3 d-none">
<p></p>
<img id="img" width="200px" />
</div>
</div>
</div>
</body>
</html>
The form is configured to submit through the submitForm() JavaScript function, which is called upon form submission. Additionally, a hidden alert section can show the uploaded image and a success message once the submission is successful.
Run project
node index.js
Open the web browser and goto http://localhost:8000
You will find this test page.
Testing
Enter the name in the input field and browse for a file to upload.
Click the submit button to send the form. You will then see a success message along with the submitted information returned from our API.
Conclusion
Express and Multer streamline the process of managing file uploads in Node.js applications. By utilizing a straightforward setup with Multer for handling file uploads and Express for routing, you can efficiently manage file submissions and enhance the overall user experience in your web projects.
Source code: https://github.com/stackpuz/Example-File-Upload-Express
Create a CRUD Web App in Minutes: https://stackpuz.com