How to Upload Images in Node.js and Express Using AJAX and jQuery
Handling asynchronous file uploads without refreshing the page provides a seamless user experience. In this tutorial, we will explore how to upload an image file using AJAX and jQuery in a Node.js and Express application.
We will use the browser's FileReader API to read the selected file as a Data URL, send the Base64-encoded payload to the server via AJAX, and save it directly to the server using Node's fs (File System) module.
Project Structure
Your project directory should be structured as follows:
upload/
├── views/
│ └── demo.ejs
├── app.js
└── package.json
Step 1: Set Up Your Project Folder
Open your command prompt or terminal and initialize a new directory for your project:
mkdir upload
cd upload
Step 2: Initialize Node.js and Install Dependencies
Initialize your Node.js environment by creating a package.json file automatically:
npm init -y
This command creates a package.json file indicating that Node is initialized in the folder.
Next, install the required packages for building the application (Express, Body-Parser, EJS, and jQuery):
npm install body-parser ejs express jquery
Step 3: Create the Frontend View (views/demo.ejs)
Create a new folder named views in your project root, and inside it, create a file named demo.ejs. This file handles the client-side form, the FileReader API preview, and the asynchronous AJAX submission.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Async File Upload with Node.js and AJAX</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
<a class="navbar-brand" href="#">UploadFile</a>
</nav>
<div class="nav justify-content-center">
<div class="card nav justify-content-center" style="width: 18rem; margin-top:7%;">
<div class="card-body text-center">
<input type="file" name="file" id="file" accept="image/*" class="form-control"><br>
<button type="button" class="btn btn-success" id="upload">uploadfile</button>
</div>
</div>
</div>
<br>
<div class="nav justify-content-center img"></div>
<script src="/jquery/jquery.js"></script>
<script>
$(document).ready(function(){
var fileData;
var myFile;
$('#file').change(function(){
var filereader = new FileReader();
filereader.onload = function(event){
fileData = event.target.result;
};
myFile = $('#file').prop('files')[0];
filereader.readAsDataURL(myFile);
});
$('#upload').click(function(){
$.ajax({
method: "post",
url: "/upload",
dataType: "JSON",
data: {'filename': myFile.name, 'file': fileData},
success: function(response){
if(response.msg == "success"){
alert('uploaded');
$('#file').val('');
$('.img').append('<img src="data:image/*;base64,'+response.data+'" style="width:300px;height:300px;margin:10px;">');
}
},
error: function(){
alert('server error');
}
});
});
});
</script>
</body>
</html>
Step 4: Configure Entry Point (app.js)
Create a new file named app.js in your root directory as the entry point for your application. Open your package.json file, update the "main" entry to "app.js", and add the start script:
"scripts": {
"start": "node app.js"
}
Now, write your server logic in app.js:
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb', parameterLimit: 50000 }));
app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/'));
app.get('/', (req, res) => {
res.render('demo');
});
app.post('/upload', (req, res) => {
const filePath = __dirname + '/' + req.body.filename;
const image = req.body.file;
const data = image.split(',')[1];
fs.writeFileSync(filePath, data, { encoding: 'base64' });
const temp = fs.readFileSync(filePath);
const buff = Buffer.from(temp);
const base64data = buff.toString('base64');
res.json({ msg: 'success', data: base64data });
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('Server running at port ' + port));
Step 5: How the Backend Code Works
- Imports & Initialization: We require
expressfor routing,body-parserfor handling form payloads, andfs(File System) for disk operations. - Body Parser Limit: Because images encoded in Base64 strings are large, we set
limit: '50mb'onbodyParser.urlencodedto prevent payload restriction errors. - Static jQuery Routing:
app.use('/jquery', ...)exposes the localnode_modulesjQuery library directly to the browser. - Rendering the View: The root route (
/) rendersdemo.ejswhen users visit the web page. - Handling the POST Upload:
- Extracts
req.body.filenameandreq.body.file. - Splits the Base64 Data URL (
image.split(',')[1]) to strip off header metadata. - Uses
fs.writeFileSync()to save the file onto the server disk. - Reads the file back into a Buffer, converts it to Base64, and responds with JSON for instant frontend preview.
- Extracts
Conclusion
By combining the browser's FileReader API with Express and body-parser, you can successfully implement fast asynchronous image uploads in your Node.js applications.
References & Source Code
Source Code: Download complete source code from GitHub
Video Tutorial: Watch Video Tutorial on YouTube
Comments
Post a Comment