-
Screenshots
-
In brief about upload.js and Usage
There is a good module for working with file uploads, called "
Multer".
Based on Multer module, i made a JavaScript class to easily upload files with node.js, with a minimum necessary code.
This class, called
uploadFile is exported as a module, and can be included with require().
Create a Node.js module to upload file with Multer
• You can create the files with the code presented in this page, or ..:
- Click this link to download the whole script:
Node.js Simple Upload Files.
1. First, we have to install the Express and Multer modules with NPM (Node.js Package Manager).
Open the command line interface and tell NPM to download these packages.
npm install --save express
npm install --save multer
2. Lets create our module that uses multer to upload files, with options to set allowed file extensions and maximum file size for upload.
In the directory of your Node.js project create a file called "
upload.js", and add this code (
click on the code to select it):
//uploads file to server with multer module
class uploadFile {
//set needed properties
constructor(){
this.multer = require('multer');
this.destination = null;
this.exts =['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt']; //allowed extensions
this.maxsize =3; //maximum allowed file size; in MB
this.rewrite = true; //true=rewrite the file if exists; false=sets the file name: 'originalname-Date.now()'
this.init();
}
/*Sets properties, receives object:
{
destination: 'folder for uploaded file' (Required, default: null)
exts: [array with allowed extensions] (Optional, default: ['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt'])
maxsize: integer number for maximum allowed file size, in MB (Optional, default: 3)
rewrite: true or false (Optional, default: true); true=rewrite the file if exists; false=sets the file name: 'originalname-timestamp'
}
*/
set setProp(o){
if(o.destination) this.destination = o.destination;
if(o.exts) this.exts = o.exts;
if(o.maxsize) this.maxsize = o.maxsize*1;
if(o.rewrite) this.rewrite = o.rewrite;
}
//set main multer objects for upload
init(){
//sets destination folder and file name
var storage = this.multer.diskStorage({
destination: (req, file, cb)=>{
cb(null, this.destination);
},
filename: (req, file, cb)=>{
this.er_ext ='No valid extension.\n Allowed extensions: '+ this.exts.join(', ');
//check extension
var ext = file.originalname.match(/\.([A-z0-9]+)$/i);
if(ext && ext[1]){
ext = ext[1];
for(var i=0; i<this.exts.length; i++){
if(this.exts[i]==ext){
this.er_ext ='';
break;
}
}
}
//if no error, sets destination file name
if(this.er_ext==''){
if(this.rewrite ===true) var fname = file.originalname;
else var fname = file.originalname.replace('.'+ext, '-'+Date.now()+'.'+ext);
cb(null, fname);
}
else return cb(new Error(this.er_ext), false);
}
});
//Acepts a single file with the name 'up_f'. This file will be stored in req.file
this.upload = this.multer({storage: storage, limits:{ fileSize: this.maxsize*1024*1024 }}).single('up_f');
}
//Posting the file upload; Receives - req=request, res=response, cb=callback function
//Returns an object in the callback function, with file data, or {err:'error message'} in case of error
post(req, res, cb){
if(this.destination ==null) return cb({err:"Set a destination folder for upload, with: dirUpload \n Example:\n upload.dirUpload = __dirname+'/uploads'"});
else {
// req.file is the `avatar` file; req.body will hold the text fields, if there were any
this.upload(req, res, (err)=>{
if(err){
if(this.er_ext !='') var re ={err:this.er_ext};
else if(err.code =='LIMIT_FILE_SIZE') var re ={err:'File to large, maximum allowed size: '+ this.maxsize +' MB'};
else var re ={err:err};
}
else {
var re = req.file;
console.log('File Uploaded');
}
return cb(re);
});
}
}
}
//assign object of uploadFile class to module.exports
module.exports = new uploadFile();
3. Now we create a ".htm" file with the upload form and Ajax code that performs the upload without loading page.
Save the following code in a file called "
form.htm", in the directory of your Node.js project:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Node.js Upload Files</title>
</head>
<body>
<h1>Node.js Upload Files</h1>
<pre id="resp">Here it shows server response</pre>
<form id="uploadf" enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="up_f" id="up_f" />
<input type="submit" value="Upload" name="submit" />
</form>
<script>
var resp = document.getElementById('resp');
var form = document.getElementById('uploadf'); //get the form
//sends form data with ajax to server
function sendFile(ev){
ev.preventDefault();
//get the form and send its data to server
var data = new FormData(form);
var req = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
req.open('post', form.action, true);
req.send(data);
//receives and parse response in JSON format
req.onreadystatechange=function(){
if(req.readyState ==4){
var obr = JSON.parse(req.responseText.replace(/\\\\/g, '/'));
if(obr){
//HERE you can parse the obr JSON object
if(obr.err) resp.innerHTML ='<h4 style="color:#ee0000">'+JSON.stringify(obr.err, null, 2).replace(/(^")|("$)/g, '').replace(/\\n/ig, '<br>')+'</h4>';
else resp.innerHTML = JSON.stringify(obr, null, 2);
}
}
};
return false;
}
// calls sendFile() on submit
form.addEventListener('submit', sendFile, false);
</script>
</body>
</html>
- The JavaScript code in the "form.htm" file sends the form to server, and displays the response in web page.
4. Now, we create a "
server.js" file that uses Express to serv the pages to browser, and the "upload.js" module to upload the file when form data is sent.
Copy and save the following code in a "server.js" file in the same directory:
const express = require('express');
const upload = require('./upload.js');
const port =8080;
const app = express();
app.set('port', port);
//Showing form.htm file on homepage
app.get('/', (req, res)=>{
res.sendFile(__dirname+'/form.htm');
});
/*
Before upload.post(), calls setProp() passing an object, to set destination folder (here 'uploads'), and other properties
Full object:
{
destination: 'folder for uploaded file' (Required, default: null)
exts: [array with allowed extensions] (Optional, default: ['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt'])
maxsize: integer number for maximum allowed file size, in MB (Optional, default: 3); 0.5 = 500 KB
rewrite: true or false (Optional, default: true); true=rewrite the file if exists; false=sets the file name: 'originalname-Date.now()'
}
*/
upload.setProp ={destination: __dirname+'/uploads', exts:['jpg', 'png', 'mp3'], maxsize:0.5};
//calls upload.post() when POST request
app.post('/upload', (req, res)=>{
//passes a callback function that receives an object with response: data of the uploaded file, or {err:'error message'} in case of error
upload.post(req, res, (re)=>{
//HERE you can parse the received object
//outputs the object response as a JSON string
res.end(JSON.stringify(re));
});
});
var server = app.listen(port, ()=>{
console.log('Listening on port ' + server.address().port);
});
- Run the "server.js" in command line interface.
node test/server.js
Access the server in your browser, on port 8080 (
//localhost:8080/ ).
- Now you can upload files on your server with Node.js.
• After the file is uploaded, the
post() method of the "upload.js" module returns an object with file data in a callback function received as argument:
{
"fieldname": "up_f",
"originalname": "dolphin.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "e:/nodejs/test_upload/uploads",
"filename": "dolphin.jpg",
"path": "e:/nodejs/test_upload/uploads/dolphin.jpg",
"size": 3752
}
- or an object with error message in case of error: "
{err:'error message'}"
Screenshots
The files for Node.js server and upload module, in a "test" directory:
Object response with data of the uploaded file:
Message in case of error:
In brief about upload.js and Usage
upload.js is a module that simplifies the code for upload files in node.js projects. It is based on the Multer module.
- To download the script, click:
Node.js Simple Upload Files
Usage:
1. Install the multer module with NPM from command line interface:
npm install --save multer
2. Copy "upload.js" and "form.htm" directly in your project directory.
3. Include "upload.js" in the Node.js server file:
const = require('./upload.js');
4. Set destination of the directory for upload files, with
upload.setProp :
upload.setProp ={destination: __dirname+'/uploads'};
- Additionally, you can set other properties too: "exts", "maxsize", "rewrite" (see the comments in the upload.js file).
5. Show "form.htm" file on browser. Example with Express:
res.sendFile(__dirname+'/form.htm');
6. Call the
upload.post() method when POST request with form data:
upload.post(req, res, callback);
"callback" is a callback function with an argument in which receives an object response from post() method.
- More important:
Have a Good life with everyone and with yourself.