File upload in node.js seems tedious due to its async nature and network programming approach. However, it is one of the easiest file upload mechanisms I have seen yet.
How to perform file upload?
I am going to use express framework and middleware called “multer”. This middleware is designed for handling the multipart/form-data.
In front-end script, we will set the “target” parameter of FORM to our router. for.eg  /upload/picture and in app.get(‘/upload/picture’, …) we will be able to handle our file. Let’s see how.
Our project:
This project is simple. We will have a simple express web server that does the task of routing and other stuff. Multer will take care of the file handling and HTML for handling form input.
#2: Upgrading to multer v 1.1.0.
"name": "file_upload",
"version": "0.0.1",
"dependencies": {
"express": "4.13.3",
"multer": "1.1.0"
},
"devDependencies": {
"should": "~7.1.0",
"mocha": "~2.3.3",
"supertest": "~1.1.0"
}
}
Installing dependency:
Save the package.json in folder and type
to install the required stuff.
This code is updated with the latest version of Multer.
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
Running project:
Copy code and save them in folder. Type
to run the project. Visit localhost:3000 to view the app. Select the file and check the uploads folder. Your file must be present there!
Explanation :
In our Server.js file, we have configured multer. We have made custom middle-ware function to choose the storage engine which is Disk because we want files to store in disk and appending the file name with current date just to keep the uniqueness of files.
After completing upload , req.files variable holds following array of information.
userPhoto:
{
fieldname: 'userPhoto',
originalname: 'banner.png',
name: 'banner1415699779303.png',
encoding: '7bit',
mimetype: 'image/png',
path: 'uploads\banner1415699779303.png',
extension: 'png',
size: 11800,
truncated: false,
buffer: null
}
}
We are initializing the multer in our /api/photo/ router and in callback we are receiving the error. If there is no error that means file is uploaded.
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
In HTML form you must mention enctype=”multipart/form-data” else multer will not work.
Performing file validation:
To perform validation on Server end, multer provides limits array parameter which have following parameters. ( Reference: Github official page. )
- fieldNameSize – integer – Max field name size (Default: 100 bytes)
- fieldSize – integer – Max field value size (Default: 1MB)
- fields – integer – Max number of non-file fields (Default: Infinity)
- fileSize – integer – For multipart forms, the max file size (in bytes) (Default: Infinity)
- files – integer – For multipart forms, the max number of file fields (Default: Infinity)
- parts – integer – For multipart forms, the max number of parts (fields + files) (Default: Infinity)
- headerPairs – integer – For multipart forms, the max number of header key=>value pairs to parse Default: 2000 (same as node’s http).
You can define it like this
fieldNameSize: 100,
files: 2,
fields: 5
}
In our code.
Conclusion:
Multer is a very useful middleware created by the Express community. It really helps us to quickly develop critical code like File uploads in Node.js easily. I hope you find this tutorial helpful.
This actually came at a perfect time for me. Currently creating an Angular, Node, Express app and file uploading was the last piece of the puzzle. Thanks!
Your most welcome. Glad it helps.
Excellent! I managed to make it working successfully in just few minutes!
Great Explaination! Thanks!
Thanks Ajit. Glad it helps you.
Hi, thanks a lot for this post, but I’m hoping that you guys can answer a question for me, I’m currently using multer, but a need a way to upload files to different directories. For example images to ‘uploads/img’, pdf files to ‘uploads/pdf’ and so on. Thanks again.
Hi Juan,
By default this feature is not available. You need to create multiple instance of multer for different file types and in each instance define the destination. Hope this snippet trigger the idea.
var mwMulter1 = multer({ dest: './uploads1/' });
app.post('/files1', mwMulter1, function(req, res) {
// check req.files for your files
});
var mwMulter2 = multer({ dest: './uploads2/' });
app.post('/files2', mwMulter2, function(req, res) {
// check req.files for your files
});
Nice tutorial! I’ve created an npm package based on it, so it’s easier to upload stuff and save them to disk:
https://www.npmjs.com/package/nodefu
Nice Tutorial
I wonder if you could tell me how to send status code 200 after update completed?
Which update Amir ?
He might mean Res.send(200,”upload complete”);?
res.status(200).send(“upload complete”);
Nice tutorial!
Thank you
Plz i want asking you of i want upload file to an oder sever node.js
Sorry ?
Hi,
I’m getting this error:
TypeError: path must be absolute or specify root to res.sendFile
I think I didn’t get what are the parameters of sendFile function
try this – res.sendFile(‘index.html’, { root: __dirname });
hello thanks for your tutorial,but now I have some problem.
I can run when I use this server.
but if I add to my server I got this Error.
Error : Request aborted at IncomingMessage.onReqAbortd ……
Thanks for the valuable post!
However I suggest you emphasize that having a name attribute for the input HTML element is compulsory for the multer to work.
I seldom used name in HTML and skipped it now too. Then multer just did not work and I was dredging all over for the fix till I found a stackoverflow tip to just add a name!!
thanks for youre great tutorial, how about upload more than one photo? thanks sir
Hello,
Thanks a lot for this great tuto.
I’ve got this message :
express deprecated res.sendfile: Use res.sendFile instead
And, when using this :
app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
}));
I’ve got this error on line 20 :
onFileUploadStart: function (file) {
^
SyntaxError: Unexpected token (
Could you help me please ?
Thanks again for the tuto,
ANDRE_Ani
You are using one extra
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
});
Thanks a lot, I’ll test this.
Thanks again for this great tuto, very usefull for a beginner like me.
hi..thanks for this tutorial..it works perfect..may i know how to display image that i already upload based on the image name saved in the database?thanks in advance..
Me again, sorry.
If I use this :
app.use(multer({ dest: ‘./uploads/’, rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
});
onFileUploadStart: function (file) {
console.log(file.originalname + ‘ is starting …’)
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
done=true;
}
}));
I have this error :
app.js:18
});
^
SyntaxError: Unexpected token ;
And for the deprecated, I have this :
TypeError: path must be absolute or specify root to res.sendFile
Sorry again, I’m a beginner…
No need for sorry.
I think there is bracket issue at the end of article. Please download the code from Github and run that.
I download and run the code from Github, and it seems good, it’s the result :
Working on port 3000
express deprecated res.sendfile: Use res.sendFile instead Server.js:20:11
live.png is starting …
userPhoto uploaded to uploads/live1432709554651.png
{ userPhoto:
{ fieldname: ‘userPhoto’,
originalname: ‘live.png’,
name: ‘live1432709554651.png’,
encoding: ‘7bit’,
mimetype: ‘image/png’,
path: ‘uploads/live1432709554651.png’,
extension: ‘png’,
size: 14153,
truncated: false,
buffer: null } }
And with the modified code for file validation :
var express = require(“express”);
var multer = require(‘multer’);
var app = express();
var done = false;
app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
}));
onFileUploadStart: function (file) {
console.log(file.originalname + ‘ is starting …’)
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
done=true;
}
}));
app.get(‘/’,function(req,res){
res.sendfile(“index.html”);
});
app.post(‘/api/photo’,function(req,res){
if(done==true){
console.log(req.files);
res.end(“File uploaded.”);
}
});
app.listen(3000,function(){
console.log(“Working on port 3000”);
});
I have this :
onFileUploadStart: function (file) {
^
SyntaxError: Unexpected token (
Oh you are using function outside of scope. Run this
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done=true;
}
}));
Thanks a lot, it’s working now 😉
It was a beginner error…
Hi
How can i upload image through Angular. I tried to use mysql database.
hi..nice tutorial..how i can display the image that stored in the uploads file?
Create express.static path to the folder you have used and in img tag of HTML put file name of uploaded image.
i have done upload process but how can i same path download!!!
I dint get your question.
my English is bad. If use app.use(express.bodyParser()) and before insert app.use(multer({/*…*/})), you example dont work. Or at the beginning
insert app.use(multer({/*…*/})) and before app.use(express.bodyParser()), how to close connection with client.
You guys can also use nodefu, which is going to be much easier than that. Peace!
https://github.com/cesarvargas00/nodefu
Hello,
I want to thank you for this tutorial. I only have a simple question. After uploading the file, how can I redirect to another html page?
Thanks
Yes on the file upload complete event, you can use HTTP response variable to redirect.
Again, thank you very much. You helped me a lot!
Pleasure is mine.
Hi man. Thanks for this tuto, it’s great. However it seems the form uploads the file even if you don’t call /api/photo. I mean, if you change the action of the form to anything, like “http://myserver”, it will upload the file anyway. So it’s not respecting the routes. Any idea why this is happening? Thanks!
Nice tutorial….,
I created multiple instance of multer for different file types and each instance defined specific destination but I am also using json web tokens for authentication. In this case i am getting TypeError: Cannot read property ‘token’ of undefined. Is it possible to use both different multers and json webtokens? but Whenever upload all files into single destination i didn’t get any error.
Is it possible to use both json web token and multiple instances of multer?
nice tutorial…
How do I upload a file from an application (e,g, from a perl script or java script) and not through a browser but using this node server. Appreciate any pointers in this regard.
In addition to the browser form upload, I would like to upload files through an application (like Perlscript or node javascript) and using the same server. Appreciate any pointers in this regard.
What would be your source ? From where you wanna upload file ? If i get it right its server to server then you don’t need upload. Just move them from one location to another.
Of course it is from client to the server. Client will run an application and that will make a post to server and transfer/upload a file.
var multer = require(‘multer’);
var mwMulter1 = multer({ dest: ‘./uploads1/’ });
app.post(‘/files1’, mwMulter1, function(req, res) {
// check req.files for your files
});
var mwMulter2 = multer({ dest: ‘./uploads2/’ });
app.post(‘/files2’, mwMulter2, function(req, res) {
// check req.files for your files
});
I am using this code to upload images into different folders it is working fine but i am not getting post data it simply display undefined format. the code look like this.
app.post(‘/test’, function(req, res){
var name = req.body.name;
console.log(“Name is — “+name);
res.json(“name sent to server”);
You need to store file name in some variable at multer middleware.
First of all, thanks for your tutorial. But I’m trying to use it and it doesn’t work. In my case, I don’t have the upload form in the index page, but in a secondary page (located in a directory, ‘partials/upload.jade’, I use Jade for make my pages) I also use AngularJS… Should it be a problem? I follow all your tutorial step by step, the only difference is what I have mentioned.
Thank you in advance.
Until and unless its Form request to backend, its not a problem. Can you share your angular code so that i can help !
Of course, here is my main Node.js file (in your case the “server.js”):
https://github.com/lousan92/genealogical-tree/blob/master/app.js
And that’s the Jade file which contains the form:
https://github.com/lousan92/genealogical-tree/blob/master/views/partials/upload.jade
There’s also a problem: if I add “method=’POST'” to the form, it appears a message saying me “Cannot GET /api/uploadFile?”. If not, the browser doesn’t charge anything.
Another thing to say is that I have my APIs in a separate page, but once again it shouldn’t be a problem if I have the upload API with a direct callback function in the main file, am I wrong? Because I need the “done” boolean I guess.
Thank you again and sorry for the double post, I thought that it wasn’t sent!
Sorry for late reply.
Server code looks good.
In form code, just remove enctype and use “method” = “POST” and try same.
Let me know the result.
It still doesn’t work. But now I’ve discovered that any of my POST APIs work when I configure Multer, and I don’t know why (I have a form to add data to the database, and in normal conditions it works, but when I add your code to configure Multer I can’t do it).
Sorry, now the other APIs seem to work fine with Multer. But the “upload” one continues without working, following your steps.
(And sorry again for double posting, I used the inline comments thinking that it was the reply button)
Hi again, don’t worry about that: I’ve finally been able to make the code work (if you ask me, I don’t know how :P). Thanks again 🙂
Nice tutorial, but I’m trying to follow your steps and I’m not able to upload files. When I click the Upload button, the browser tells me “Cannot GET /api/uploadFile?”. I have more APIs in my project, and all of them work without problems (I have tried with another ones in that form and they work). What could happen? Multer is configured as you did and I’ve put the “api/uploadFile” line (the name I’ve used) in the same way as you.
Thank you in advance.
TypeError: app.use() requires middleware functions
at EventEmitter.use (D:UsersFINCHDesktopNodenode_modulesexpresslibap
I copied your exact code. The error is pointing to this line:
app.use(multer({ dest: ‘./uploads/’,……
Hi. First of all, thanks for the tutorial. I have the same error.
Any idea?
Thanks.
Well it can’t be coincidence that two people have same issue. Let me check it again. Please give me little time.
I just executed the script. Looks fine to me. Can you clone this https://github.com/codeforgeek/File-upload-in-Node and run.
It still doesn’t work. But now I’ve discovered that any of my POST APIs work when I configure Multer, and I don’t know why (I have a form to add data to the database, and in normal conditions it works, but when I add your code to configure Multer I can’t do it).
Looks good but just cannot make it work, this is ubuntu 12.04, installed node 0.12.7, express 4.13.1.
made 1 change to app.use: added single().
app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ‘ is starting …’)
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
done=true;
}
}).single(‘userPhoto’));
i do see file gets uploaded successfully, it’s a picture, opens fine.
BUT never hits onFileUploadStart, onFileUploadComplete. Webpage just keeps on waiting and never hits if(done==true)
Any help appreciated.
Even me too facing the same issue, any help on this…
Hi, I am trying to insert image into mongodb using angularjs and nodejs using mongojs module, can any one suggest me how can I do this thing????
Are you uploading file and inserting its path OR inserting binary data into database ?
Thank You 🙂
Your welcome 🙂
I succeeded in uploading file, but the file doesn’t have its extension. Why is that?
Hi ! Thanks for this tutorial. I have a question to ask you =)
I would want to upload a form containing a video file and parameters, such as :
“formData.append(‘media_format’, extension);
formData.append(‘media’, blob);
formData.append(‘mediaid’, id);”
But I can’t seem to find where in your code I could put those infos. Is this automatically taken care of when you send the form from your .html client file to your .js server file ?
You will get all file information in console.log(req.files)
Hi,
thanks for great tutorial. Got everything working with one exception.
I’m printing req.files with console.log and it’s returning only { userPhoto:
and nothing else from the array. If I try to print directly other item from the array, it returns undefined. Any idea why is it doing this?
Thanks again.
Thanks for the tutorial, it really helped. I have a question, hopefully you can help me out.
From what I’m seeing, ‘done’ is a global variable, right? If you have multiple users uploading files at the same time, will the variable be set to true as soon as the first upload finishes? Wouldn’t that affect the other users?
Or does onFileUploadComplete emit just to the user that’s uploading?
Your doubt is correct. It may overwrite global value. Possible solution will be store that information in third party storage. Could be Redis.
Hi Andrew,
I have updated the code now with more router specific file upload.
You can pull the changes from github too.
i do see file gets uploaded successfully,
BUT never hits onFileUploadStart, onFileUploadComplete. Webpage just keeps on waiting and never hits if(done==true)
& file extension is also missing
Any help appreciated.
Have you used same code from Github ?
Hey, i think i got where you are confused with. done == true is hitting and that is why console is printing req.files object. About res.end, you can see that in browser console cause we are not rendering our pages from Node script. We used res.sendFile to send HTML page to browser.
for this line,
app.post(‘/files1’, mwMulter1, function(req, res) {
});
im getting error like this
Route.post() requires callback functions but got a [object Object]
Hi,
for the line
app.post(‘/files1’, mwMulter1, function(req, res) {
// check req.files for your files
});
im getting error like this.
Route.post() requires callback functions but got a [object Object]
can you please help me.
You are doing it wrong. You need to configure it in Express object. Please see the code.
Are you telling about mwMulter1 ??
Yes.
app.post is router. You need to configure multer in middleware.
I have done like this
var multer = require(‘multer’);
var mwMulter1 = multer({ dest: ‘./uploads1/’ });
app.post(‘/files1’, mwMulter1, function(req, res) {
// check req.files for your files
});
Hi,
for the line
app.post(‘/files1’, mwMulter1, function(req, res) {
// check req.files for your files
});
as you have suggested for Juan Irizar,
its throwing error like this,
Route.post() requires callback functions but got a [object Object].
Can you please help?
good stuff! Thank you.
Its cool way to upload, but i need to upload to picasa..
Thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Thank Q shahid for this post
Thank u, for this helpful post. But, can we upload the images in using this in drag-and-drop manner also..? Please confirm..
Thanks for the tutorial, it really helped. I have a question, hopefully you can help me out.
my question is how to create file uploading in node js but one think is there register user are id used to folder name to create server site.there folder name is updeted user id for the folder.plz help me.
You need folder for each user id and images or files in that folder ? is it what you asked ?
ya sir i need new folder created in each user id to save in the mongoose in mongodb to fech this id and create folder in node.js server side.
i am created new registration form to used in restful api in this registration are complited it will genrat on id this id are fech in server side and newly create folder in server.
ex. user/uploads/123(id fech in mongodb)
user/uploads/124
plz help me…
please am a newbe to nodejs this this handle large file upload upto 1gb thanks
this is not working
app.use(multer({dest:’./uploads/’}).single(‘photo’));
.single(‘photo’)); is missing…
also it gives typeerror bcoz upload is not function
single is optional and this code is not for photo specific. Give me error stack, this code works perfectly.
I got this. This is due to upgrade of Multer. I am updating code with latest version of Multer.
Upgraded the code. Have a look.
Now I am getting below
Error uploading file.Error: ENOENT, open ‘folderpath\userPhoto-1450888354667’
Got it working…thanks….now uploads folder needs to be created earlier.
Hello does multer or any of the other Node.js upload libraries have an overwrite option that will prevent the renaming behavior and just overwrite the file if it already exists. Thanks
Nope.
But you can write function which do that before uploading a file into system. Use “FS” module function to check the existence and if exist delete that.
Ah ok thank you
I know this is late, but for anyone else reading this, I’m finding the default action by multer IS to overwrite the file if it already exists.
Hey How do I know where the file was uploaded?like if I want to see the image uploaded, what url willl i have to go to? Does it save the image to the “uploads” folder you created?
Ya it uploads there only.
hi, how to check the user validation before file get uploaded. the file should upload once the user is valid.
Hi!
nice article! I think there is a minor error on the limit example. Where it says:
var upload = multer({ storage : storage},{limits : {fieldNameSize : 10}}).single(‘userPhoto’);
I think it should say:
var upload = multer({ storage : storage, limits : {fieldNameSize : 10}}).single(‘userPhoto’);
Otherwise the limits are not taken into consideration.
Regards,
V.
Thanks, How can i get and display the image after i finish to upload ?
Thanks, How can I get and display the image after upload it finish?
Hi,
After you submit the file successfully to node server, you need to return back the response with file path which you can access in req.files.path variable. And in UI, upon recieving success response, show that path using
tag. That’s it.
How to display the image after I finish upload to image?
Please Help me
Hi,
After you submit the file successfully to node server, you need to return back the response with file path which you can access in req.files.path variable. And in UI, upon recieving success response, show that path using
tag. That’s it.
hello sahid, i have followed your tutorial, but i changed only the destination specify function to this var upload = multer({dest: __base +’/public/uploads’}).single(‘userPhoto’); but after uploading an image, the file type uploaded was “File” with the name like 887710ec416ef7f448905f8a0a7509a0. what is going on with my code?
var multer = require(‘multer’);
var upload = multer({dest: __base +’/public/uploads’}).single(‘userPhoto’);
app.get(‘/uploads’,function(req,res){
res.sendFile(__base +”/public/views/index.html”);
});
app.post(‘/upload’, function(req, res){
upload(req, res, function(err){
if (err) {return res.end(“error uploading file.”);}
// res.send(req.files);
res.end(“file uploaded”);
})
})
Hey shahid,
Nice work there.
I wonder you could guide me how to handle errors which come when file size is exceeded and also when the format is incorrect. I also want to send an error response to client when the above errors occur. I knew my way around before multer 1.1.0. Please guide me how to do this in multer 1.1.0. I can’t seem to find a way out.
Thanks.
Hey shahid,
Nice work there.
I wonder you could guide me how to handle errors which come when file size is exceeded and also when the format is incorrect. I knew my way around before multer 1.1.0. Please guide me how to do this in multer 1.1.0. I can’t seem to find a way out.
Thanks
Replied on your email.
Here is snippet for everyone looking out for same.
{
storage : storage,
fileFilter : function(req, file, callback) {
var fileType = ['xls','xlsx'];
if (fileType.indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
}
}).single('userPhoto');
Hey Shahid,
Kudos to you and the codeforgeek for doing such an awesome job to help newbies like us out.
I did as you told but have run into a new problem.
The limits option does not seem to work.
I have handled the error in the function inside the route(‘/dp’ is my action for uploads)
When I upload a large file, the response “SIZ” is send after a long time proportional to the size of the file being uploaded indicating that upload is not being aborted and limits is failing. Am I missing something here?
My upload object definiton.
var maxSize = 1 * 1024 * 1024;
var upload = multer({ dest: ‘./bin/uploads/’,
limits: {
fileSize: maxSize,
files: 1
},
filename: function (req, file, callback) {
callback(null, file.fieldname + ‘-‘ + Date.now());
}
fileFilter: function (req, file, cb) {
var ext = path.extname(file.originalname);
if (ext !== ‘.jpg’ && ext !== ‘.png’ && ext!== ‘.gif’ && ext!== ‘.bmp’ ) {
console.log(“File extension violated”);
// throw error;
return cb(null, false)
}
cb(null, true);
}
}).single(‘avatar’)
My route where upload is being handled.
app.post(‘/dp’ , function(req ,res){
upload(req,res,function(err) {
if(err) {
console.log(“ERROR multer 1.1.0–>”+err);
var er_string = String(err);
console.log(typeof er_string);
console.log(“er_string “+ er_string)
if(er_string==”Error: EXT”)
{
console.log(“res send err format”);
res.end(“FRMT”);
}
else
{
res.end(“SIZ”);
}
Hello shahid i have problem in node.js.
I am trying to build an web based application, wherein i take the snapshots of my sites visitors and store them in database( for now its simply a folder ). Server side is controlled with node.js. But the problem is, if i have a image with name say “xyz.png” and if i again try to put a image with the same name in the same folder, latter image gets appended with the previous one (“xyz.png”). The only thing happens is that the size of latter image increases.
Its happening because i am appending the images to the folder content (because i am using opening it with ‘a’ flag).
This is the piece of code:
//fileName is the image name that i want to store
fs.open(fileName, ‘a’, 0755, function(err, fd) {
if (err) throw err;
fs.write(fd, buffer, null, ‘Binary’, function(err, written, buff) {
fs.close(fd, function() {
console.log(‘File saved successful!’);
});
})
});
Is there any other way of doing this thing. As i don’t want to loose my previous content of the folder.
Hi,
Yes you should check the existence of file using fs.exists() before doing append. Append only when you need, for eg. text file should be appended, not images i think.
Hi Shahid
I have problem in node.js while uploading file from html
i am using express framework for my application
app.js file
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, ‘./uploads’);
},
filename: function (req, file, callback) {
callback(null, file.fieldname + ‘-‘ + Date.now());
}
});
var upload = multer({ storage : storage}).single(‘userPhoto’);
app.post(‘/api/photo’,function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end(“Error uploading file.”);
}
res.end(“File is uploaded”);
});
});
Html form
name
Upload file
What is the problem ?
Everything works great. But upon uploading. What is get is NOT an image file….
its a different kind of file. …
its because of renaming with the date. I’ll update it to preserve the extension.
Hi, great Application ! Just one question, Is possible to use this application on same port of another application ? I need to use my application that works on port 8888 and this application oh the same port, but when I try, I have a javascript error (TypeError: status is not a function)
No port must be different.
var express = require(“express”);
var multer = require(‘multer’);
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, ‘./uploads’);
},
filename: function (req, file, callback) {
callback(null, file.fieldname + ‘-‘ + Date.now());
}
});
var upload = multer({
storage: storage
}).single(‘userPhoto’);
app.get(‘/’, function (req, res) {
res.sendFile(__dirname + “/index.htm”);
});
app.post(‘/api/photo’, function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end(“Error uploading file.”);
}
res.end(“File is uploaded”);
});
});
app.listen(3000, function () {
console.log(“Working on port 3000”);
});
errors shows that Error uploading file.
i am beginer please help me to solve that problem…
Do you have uploads folder in place and permission is ok ?
Could you please tell me that how can we upload more than one file ?
Here it is.
thank you for the tutorial..
im making rest api with nodejs.
and i use this turorial for uploading, but i just want to have the path of the uploaded files stored on mongodb, how to do it? pls help thanks
thank you, for this awesome tutorial!
can you help me to get the uploaded file path, and stored that in mongodb.
im using nodejs, express, and monk
hello. im new to nodejs and but express.
can u tell me how i will get the file i upload, to be displayed in the client side, from mongodb. (im assuming i have to take the path of the files, and put it into the datbase) but i still kinda confuse of that, can u give me the simple tutorial/example?
nice tutorial u give here btw.Thanks
Sorry for late reply Daniel.
To answer your question, you can get the uploaded file by storing the path variable present in req.files and return it to client to view the file.
For. eg :
Insert value present req.files.userPhoto.path variable in Mongo and return it using GET api or in response of file submit to view it on client 🙂
tahnks for answering the question..
but, how the client can get to the folder that i stored my files to, my server and the client has different origin. since the req.file.path wil only return ../”folder upload”/”filename”
how the clinet can use this path to access the files.
im assuming this has something with express.static(path) ,but i dont really understand, can u explain this ? thankyou
Yes, you are right about express.static().
You need to add that folder as a static path where your file is getting uploaded and once the client is trying to access that, express will automatically resolve the path.
Assuming folder is uploads, add this in your app file ( assuming the app is in the main directory and not in the sub directory).
If above doesn’t work, try using path.
app.use(express.static(path.join(__dirname,'./uploads')));
thanks a lot man. u help a lot.
Thank you for your great tutorial!
Your code run very well but the test has some problems, I can’t get req.file when I run the test, its always undefined. Can you somehow help me with this?
Thank You for a great tutorial
I am still new to node and express,The file uploads work great,however I wanted to know how to get the files to display on my client side
After file successfully upload, send the path back to the client.
Will update code soon.
Hello,
I’m a beginner at this and I have the same problem. I’m trying to figure it out but I’m not getting it right. I was wondering if you have the code for this somewhere?
Thank you in advance 🙂
Thank you for the tutorial, Could you explain if I can use multer for below scenario and if Yes, where should i specify destination host name and port?
If I want to upload a file from my machine to a different machine where the application is hosted(server), will I be able to do it using multer. I mean I will host a web application on machine one which serves as server and i will access it through the browser of machine 2 which is client. I will upload a file from machine 2 , but it should get uploaded to the server(machine 1).
Hi,
Is it possible to use multer to upload file to a different machine
Hi sir,
I am beginner in node js, i run the same code what you have given. But i am getting error as below
TypeError: status is not a function
[Break On This Error]
status(‘Error: ‘ + xhr.status);
please tell me hoe to clear this
How are you running the code?
i installed node js in my pc (ubuntu 10.04LTS) and i copied codes from here and i was trying to access it from browser.
Hi,
How to upload shell scripts (.sh files )and run it using node js? please help me
Hi , Please help me here …….I want to upload diffrent extension files like .txt or excel….. and give path of directory at run time where i hv to upload that file….. can you plz help me …plz comment as soon as possible
Upload path is dynamic ?
Hi ,
Can we upload files from the local to the server using the https protocol also?
Because I am not able to uploads files in https but the same works in http.
Please help.
Thanks in advance
Thanks for this nice post on uploading files in express js.
But, a question that i faced, is that if I use other input fields along with file field my file is uploaded but the other input data from the form can not be retrieved, It is showing undefined. What is the problem, Can you please answer?
I want to downloaded uploaded file by browser.
How I can do it, help me please?
app.get(‘/’,function(req,res){
res.sendFile(__dirname + “/index.html”);
});
P.S. Thank you it’s very cool example!
This tutorial works great on my local machine. I’m trying to get it to work on my server. I get all the data back with no errors when I upload but the files don’t actually store. Is there a setting in nginx config that I’m missing?
Not really.
Make sure permission is set properly.
Hi thanks for this tutorial. how to upload .sh (ex: test.sh) files and run/execute those in back end, any body help me please…as soon as possible.
You can use Node.js child process to execute .sh files.
I tried, but its not executing completely and not showing any error.
var express = require(“express”);
var bodyParser = require(“body-parser”);
var multer = require(‘multer’);
var app = express();
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, ‘./uploads’);
},
filename: function (req, file, callback) {
callback(null, file.fieldname + ‘-‘ + Date.now());
}
});
var upload = multer({ storage : storage }).array(‘use’,2);
app.get(‘/’,function(req,res){
res.sendFile(__dirname + “/index.html”);
});
//script execution testing
var sys = require(‘sys’);
var exec = require(‘child_process’).exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec(“/root/test.sh”, puts);
app.post(‘/api/photo’,function(req,res){
upload(req,res,function(err) {
//console.log(req.body);
//console.log(req.files);
if(err) {
return res.end(“Error uploading file.”);
}
res.end(“File is uploaded”);
});
});
app.listen(3000,function(){
console.log(“Working on port 3000”);
});
This is what i am using(server.js), in above code i am giving filename along with path (/root/test.sh) what i am going to upload from browser. How to avoid this and make it general one.
Thanks in advance
Hey will this work with mocha version “^1.20.0”?
as i am using this version for my project.
and also the express version is “^4.3.0”
and should version is “^5.2.0”
and supertest version is “^0.9.0”
will it work with this version or i need to upgrade them all?
Yes it will.
I am getting an Error- Error Uploading File
I have simply copied your code if server.js and index.html I am newbie to node.js help me
Download the code and run it rather than copy paste – You might be missing some dependency.
https://github.com/codeforgeek/File-upload-in-Node/archive/master.zip
I have installed all the dependencies that is express and multer but still it was not working
do I need to make a file or something like that
Thanks so much for your tutorial! There were some oddities, going through it, but in the end I was able to figure everything out that I wanted. I whipped up a system that restricts by file type and size, and checks for a file of the same name before writing to disk. If it’s there, it renames it. Here’s my code for anyone interested (and yes, I realize my renamePng function is redundant.):
var multer = require('multer');
var fs = require('fs');
var app = express();
var renamePng = function(incomingName) {
return incomingName.replace(/\..*/i, '') + '.png';
}
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
var finalName = renamePng(file.originalname);
fs.open('./uploads/' + finalName, 'r', (err, fd) => {
if (err) {
console.error('Uploading new file: ' + finalName);
callback(null, finalName);
} else { // file exists, use generated name
finalName = finalName.replace('.png', '-COPY-' + Date.now() + '.png');
console.error('File already exists. Using new name: ' + finalName);
callback(null, finalName);
}
});
}
});
var upload = multer({
storage : storage,
fileFilter : function(req, file, callback) {
var fileType = ['png'];
if (fileType.indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
},
limits : {
fieldNameSize : 50,
files: 1,
fields: 1,
fileSize: 350000
}
}).single('userPhoto');
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file. " + err);
}
res.end("File is uploaded: " + renamePng(req.file.filename));
});
});
app.listen(3030,function(){
console.log("Working on port 3030");
});
Thanks again. (just replying once more to turn on follow-up comment emails)
Awesome Dan!
Appreciate the code.
I will update the post with your code as soon as possible 🙂
Thanks for the tutorial, it’s really helpful.
I still have a question: I’m uploading an image and I get it without an extension, so when I try to open it with a double click, I’m getting some weird characters. I also tried to open in in a browser using html but I’m still getting a broken image.
Can someone help me, please?
Thanks!
Hi,
You can avoid it by commenting this code.
callback(null, file.fieldname + '-' + Date.now());
}
Hello sir,
After commenting this code.Still i am getting image name like 449d80163ce1331437734410c07cc7f3 without any extension.
Hello, I was wondering if you can take a look at my stackoverflow post: http://stackoverflow.com/questions/41623855/multer-isnt-passing-in-express-put-route
I can do the same thing inside a put route, right?
Yes I think you can use it.
I am bigganer. I want uploading file in postman using multer. how to write api code in app.js , server.js and how to cal postman. It’s urgent please send file…
Hi,
How can i access the file name inside my app.post().
I want to access the file name and store it in db so how can i get the files name ?? I need the filename that the multer used not the name by which user uploaded.
Insider multer upload block. You can use req.files variable to access various details of files 🙂
I am also not very clear with that. Have you already finished it? can you share an example?
Where will the file being stored?
You do not need a fs.writefile to store the uploaded file?
Multer does have that fs.writeFile code.
Hi,
is there any way to post an image using node js through REST API?
No I don’t think so you can.
assalamu’alikum brother
I want to ask about this.
can u help me please
i use multer for upload image
console.log(reg.file) can be found
{ fieldname: ‘ava
originalname: ‘
encoding: ‘7bit
mimetype: ‘imag
buffer: ,
size: 396611 }
but image, cannot be move to folder
http://prntscr.com/et77v4
what is missing, brother ?
Hi, I got this error. Search google but not found any solution. Can you help me?
{“errno”:-4058,”code”:”ENOENT”,”syscall”:”open”,”path”:”E:\\node\\test-project\\uploads\\userPhoto-1493287438830″,”storageErrors”:[]}
Thank you
Hello Sir,
I coudn’t get other fields other than images.
var express = require(“express”);
var multer = require(‘multer’);
var bodyparser = require(‘body-parser’);
var app = express();
//app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, ‘./uploads’);
},
filename: function(req, file, callback) {
callback(null, Date.now() + ‘-‘ + file.originalname);
}
});
var upload = multer({ storage: storage }).single(‘userPhoto’);
app.get(‘/’, function(req, res) {
res.sendFile(__dirname + “/index.html”);
});
app.post(‘/api/photo’, function(req, res) {
console.log(‘—————‘);
console.log(req.body.username);
console.log(‘—————‘);
upload(req, res, function(err) {
if (err) {
return res.end(“Error uploading file.”);
}
res.end(“File is uploaded”);
});
});
app.listen(3000, function() {
console.log(“Working on port 3000”);
});
How do I post image or files using postman client?
Help….
File successfully uploaded., But it doest have file extention..
Thankyou…
File i have to upload some other domin url folder is this possible using multer
hello would you please tell me how i can create login and signup api in node step by step on server i am using agular in front end .
I don’t know why my code is not running and I have installed all dependencies still getting an error .
Please tell me the error.
Hi,
uploading .docx files I get a syntax error for not well-formatted XML seems that page parse calls like standard XML instead of .docx header how can I resolve it
thanks in advance
best regards
server listen on the port: :: 1515
{
file: {
name: ‘4_Application_Form_Lecturer_Tech.Asst._Librarian (1).doc’,
data: ,
size: 163328,
encoding: ‘7bit’,
tempFilePath: ‘\\tmp\\tmp-1-1563270649714’,
truncated: false,
mimetype: ‘application/octet-stream’,
md5: ’50f936beb3e0cad2c72519c0bc67da62′,
mv: [Function: mv]
}
}
ReferenceError: _dirname is not defined
at D:\uploadfile\server.js:37:12
at Layer.handle [as handle_request] (D:\uploadfile\node_modules\express\lib\router\layer.js:95:5)
at next (D:\uploadfile\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\uploadfile\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\uploadfile\node_modules\express\lib\router\layer.js:95:5)
at D:\uploadfile\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\uploadfile\node_modules\express\lib\router\index.js:335:12)
at next (D:\uploadfile\node_modules\express\lib\router\index.js:275:10)
at Busboy. (D:\uploadfile\node_modules\express-fileupload\lib\processMultipart.js:82:5)
at Busboy.emit (events.js:205:15)
sir actully i want to upload the file but there is a problem in the “_dirname ”
is there a soll
Hi……Thank you for your support…….I have a question…suppose after the file is uploaded and you wanted the user to be able to change the file, and update it if necessary. How can this be done?
Great, good article, i’m go to practice based in this post. Very good
Hi Shahid, can you please help me, How to write the API for abort file upload in mongoDB using NodeJS?