I wanted to upload images using nodeJS and multer, so I did the following:
Below is my multer configuration:
var multer = require('multer');
var storage = multer.diskStorage({
//Setting up destination and filename for uploads
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname);
}
});
var upload = multer({
storage: storage,
limits:{
fieldSize: 1024*1024*6,
}
});
Below is my route to upload image:
router.post('/designer', upload.single('designerImage'), async (req, res) => {
console.log(req.file);
//rest of the code which is not needed for my query
})
It works perfectly fine when I POST the file using form-data key of type file using POSTMAN. But when I try to send it using a HTML form input, req.file comes out to be undefined and no file gets uploaded to the uploads folder. Below is my HTML form code:
<form action="/designer" method="POST">
<input type="file" name="designerImage">
<form>
What is the solution to this problem? I've spend hours but couldn't get to a solution.
multer only parses multipart/form-data requests, so you need to add enctype="multipart/form-data" to your form
<form action="/designer" method="POST" enctype="multipart/form-data">
<input type="file" name="designerImage">
<form>
I'm using nodejs as backend and vuejs as front. I've uploaded somes files as test using postman to my backend, but, how could I display these uploaded files using multer?
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage }).single('logo');
router.post('/logo', auth.authorize, (req, res, next) => {
upload(req, res, (err) => {
});
res.status(200).send('uploaded');
});
I got an image named 'logo-1531296527722' in my api public folder. If I try to use it in my img src (http://localhost:3000/api/company/public/logo-1531296527722) it doesn't displayed. If I try to access this route I got this error Cannot GET /api/company/public/logo-1531296527722. In all questions about that, nodejs has its own html processor like ejs or jade, but I my case, nodejs is just serving my front and all images must be rendered using vuejs.
I dit it!
In my app.js I include app.use('/dist', express.static(path.join(__dirname + '/dist')));
When i upload my form (which just contains an image), the image goes in the root folder, but I would like it to go to /public/images. I have a separate routes.js file to handle routes. This is how I've set up multer (in my routes.js file).
var multer = require('multer');
var upload = multer({dest: '/public'});
The route for the POST request looks like this:
app.post('/upload', isLoggedIn, upload.single('file'), function (req, res) {
var file = __dirname + req.file.filename;
fs.rename(req.file.path, file, function (err) {
if (err) {
console.log(err);
res.send(500);
} else {
res.json({
message: 'File uploaded successfully',
filename: req.file.filename
});
console.log(file);
}
});
});
, and the form itself looks like this (it's an ejs file):
<form method="post" action="/upload" enctype="multipart/form-data">
<label for="profilepicture">Profile picture</label>
<input type="file" name="file" accept="image/*">
<input type="submit" value="change profile picture">
</form>
You are providing a wrong path in the dest, it's a relative path so it should be dest: 'public/' instead of dest: '/public'
Also, you are moving the file from the public folder by using fs.rename and the reason it is moved to outside the root folder is you are adding the root folder in the filename and not as a path :
var file = __dirname + req.file.filename;
should be :
var file = __dirname + '/' + req.file.filename;
or even better :
var file = path.join(__dirname, req.file.filename);
Overall, a working script with no need for the fs.rename :
var multer = require('multer');
var upload = multer({dest: 'public/'});
app.post('/upload', isLoggedIn, upload.single('file'), function (req, res) {
res.json({
message: 'File uploaded successfully',
filename: req.file.filename
})
})
I am trying to write an Express-based API for uploading files. The filename and directory path should be set dynamically.
My code:
var crypto = require('crypto')
var express = require('express');
var fs = require('fs');
var mime = require('mime');
var mkdirp = require('mkdirp');
var multer = require('multer');
var app = express();
var path = './uploads';
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, path);
console.log('Im in storage destination'+path);
},
filename: function (req, file, callback) {
console.log('Im in storage filename'+path);
//callback(null, file.fieldname + '-' + Date.now());
crypto.pseudoRandomBytes(16, function (err, raw) {
callback(null, Date.now() + '.' + mime.extension(file.mimetype));
});
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.post('/photo',function(req,res){
path += '/pics/shanmu/';
console.log('Im in post , outside upload'+path);
upload(req,res,function(err) {
console.log('Im in post , inside upload'+path);
if(err) {
return res.end('Error uploading file.');
}
res.end('File is uploaded'+path);
console.log('File is uploaded'+path);
});
});
app.listen(3000,function(){
console.log('Working on port 3000');
});
My folder structure:
When I run the code, the file should be uploaded in the uploads/ folder. (This folder has two nested folders inside it - uploads/pics/shanmu).
When I triggered it from postman, it only works once. When I try the second time, I cannot upload files.
Please advise.
Working on sometime I got a solution using multer module.Using this module you can upload both files and images.And it successfully uploaded to the destination folder.
Here is my server code app.js
var express =r equire('express');
var multer = require('multer');
var path = require('path')
var app = express();
var ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/uploads')//here you can place your destination path
},
filename: function(req, file, callback) {
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
app.get('/api/file',function(req,res){
res.render('index');
});
app.post('/api/file', function(req, res) {
var upload = multer({
storage: storage}).single('userFile');
upload(req, res, function(err) {
console.log("File uploaded");
res.end('File is uploaded')
})
})
app.listen(3000,function(){
console.log("working on port 3000");
});
Create a views folder and place this index.ejs file in it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data" method="post">
<input type="file" name="userFile" />
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
After this run the server as node app.js.Open the browser and type http://localhost:3000/api/file after runnig this url choose a file which you want to upload to destination folder.And have a successfull response in both terminal and browser.Hope this helps for you.
I got your code working. See:
https://gist.github.com/lmiller1990/3f1756efc07e09eb4f44e20fdfce30a4
I think the problem was with the way you declared destination. I'm not sure why, though. I got it working by just passing the path as a string.
Best of luck!
I'm attempting to get a simple file upload mechanism working with Express 4.0 but I keep getting undefined for req.files in the app.post body. Here is the relevant code:
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//...
app.use(bodyParser({ uploadDir: path.join(__dirname, 'files'), keepExtensions: true }));
app.use(methodOverride());
//...
app.post('/fileupload', function (req, res) {
console.log(req.files);
res.send('ok');
});
.. and the accompanying Pug code:
form(name="uploader", action="/fileupload", method="post", enctype="multipart/form-data")
input(type="file", name="file", id="file")
input(type="submit", value="Upload")
Solution
Thanks to the response by mscdex below, I've switched to using busboy instead of bodyParser:
var fs = require('fs');
var busboy = require('connect-busboy');
//...
app.use(busboy());
//...
app.post('/fileupload', function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
});
The body-parser module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
For multipart, you'd need to use something like connect-busboy or multer or connect-multiparty (multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed. It comes with an Express middleware and can also be used separately.
Here is what i found googling around:
var fileupload = require("express-fileupload");
app.use(fileupload());
Which is pretty simple mechanism for uploads
app.post("/upload", function(req, res)
{
var file;
if(!req.files)
{
res.send("File was not found");
return;
}
file = req.files.FormFieldName; // here is the field name of the form
res.send("File Uploaded");
});
1) Make sure that your file is really sent from the client side. For example you can check it in Chrome Console:
screenshot
2) Here is the basic example of NodeJS backend:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
app.use(fileUpload()); // Don't forget this line!
app.post('/upload', function(req, res) {
console.log(req.files);
res.send('UPLOADED!!!');
});
It looks like body-parser did support uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency
After looking through some of the modules in mscdex's answer, I found that express-busboy was a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.
console.log(req.files) using body-parser (Express 3) output an object that looked like this:
{ file:
{ fieldName: 'file',
originalFilename: '360px-Cute_Monkey_cropped.jpg',
name: '360px-Cute_Monkey_cropped.jpg'
path: 'uploads/6323-16v7rc.jpg',
type: 'image/jpeg',
headers:
{ 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
'content-type': 'image/jpeg' },
ws:
WriteStream { /* ... */ },
size: 48614 } }
compared to console.log(req.files) using express-busboy (Express 4):
{ file:
{ field: 'file',
filename: '360px-Cute_Monkey_cropped.jpg',
file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
mimetype: 'image/jpeg',
encoding: '7bit',
truncated: false
uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }
multer is a middleware which handles “multipart/form-data” and magically & makes the uploaded files and form data available to us in request as request.files and request.body.
installing multer :- npm install multer --save
in .html file:-
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="hidden" name="msgtype" value="2"/>
<input type="file" name="avatar" />
<input type="submit" value="Upload" />
</form>
in .js file:-
var express = require('express');
var multer = require('multer');
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
var upload = multer({ dest: 'uploads/' });
app.use(function (req, res, next) {
console.log(req.files); // JSON Object
next();
});
server.listen(port, function () {
console.log('Server successfully running at:-', port);
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/file-upload.html');
})
app.post('/upload', upload.single('avatar'), function(req, res) {
console.log(req.files); // JSON Object
});
Hope this helps!
Please use below code
app.use(fileUpload());
Just to add to answers above, you can streamline the use of express-fileupload to just a single route that needs it, instead of adding it to the every route.
let fileupload = require("express-fileupload");
...
//Make sure to call fileUpload to get the true handler
app.post("/upload", fileupload(), function(req, res){
...
});
A package installation needs for this functionality, There are many of them but I personally prefer "express-fileupload". just install this by "npm i express-fileupload" command in the terminal and then use this in your root file
const fileUpload = require("express-fileupload");
app.use(fileUpload());
PROBLEM SOLVED !!!!!!!
Turns out the storage function DID NOT run even once.
because i had to include app.use(upload) as upload = multer({storage}).single('file');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './storage')
},
filename: function (req, file, cb) {
console.log(file) // this didn't print anything out so i assumed it was never excuted
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({storage}).single('file');
I added multer as global middleware before methodOverride middleware,
and it worked in router.put as well.
const upload = multer({
storage: storage
}).single('featuredImage');
app.use(upload);
app.use(methodOverride(function (req, res) {
...
}));
With Formidable :
const formidable = require('formidable');
app.post('/api/upload', (req, res, next) => {
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
res.json({ fields, files });
});
});
https://www.npmjs.com/package/formidable
You can use express-fileupload npm package to decode files like
const fileUpload = require('express-fileupload');
app.use(fileUpload({useTempFile: true}))
Note: I am using cloudinary to upload image
enter image description here
express-fileupload looks like the only middleware that still works these days.
With the same example, multer and connect-multiparty gives an undefined value of req.file or req.files, but express-fileupload works.
And there are a lot of questions and issues raised about the empty value of req.file/req.files.