Multer Doesn't Save Images in Local Folder - node.js

Multer cannot store the file, where the destination is in public/my-uploads
const express = require('express');
const app = express();
const multer = require('multer');
let storage = multer.diskStorage({
destination: '/public/my-uploads',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({dest:'storage/'}).single('file');
app.post('/upload', upload, (req , res) => {
console.log(req.files) // this does log the uploaded image data.
})

Try this File Storage For Save image in Local
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(
null,
new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname
);
},
});
This happens because you are using windowsOS and where you learned it may be using macOS in windows Path have to setted as mentioned in the above code.
You simply set the file name as given in my answer and destination is root dir "./images"...

Related

Nodejs express multer file upload + path contains double slashes

I'm trying to upload an image to my directory using Postman. I am using Nodejs and multer as a middleware.
However, I get an ENOENT error:
My question is as follows, why does my code give double \\, and what can I do to change double backslashes to forward slash in the pathname?
My code so far is:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '.test/');
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
router.post('/', upload.single('productImage'), (req, res, next) => {
console.log(req.file);
...
...
...
I have tried using the .replace() method without any success.
const multer = require('multer');
let destination = '.uploads/';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, destination.replace('\\','/'));
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
I have also tried searching similar posts here on StackOverflow, e.g trying this posts answer Error: ENOENT: no such file or directory,
You can use path.normalize('\\dsgsd\\sdgsdg') method. You can find it in official NodeJS documentation https://nodejs.org/api/path.html#path_path_normalize_path
const multer = require('multer');
const { normalize } = require('path')
let destination = '.uploads/';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, normalize(destination));
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
I found the answer after a bit of googling.
The problem was not the double \\, they are allowed, the problem was in the way the filename was saved. The filename was of a datestring, and was saved in the format: 2020-11-25T12:15something, the problem is that Windows OS does not accept files with the character ":".
Solution would be to replace this line of code :
cb(null, new Date().toISOString() + file.originalname);
with
cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);
Original answer here

How to create folder automatically before files upload via multer so that those files get stored in that created folder in nodejs?

This is my multer code to upload multiple files.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/files/'+ req.user.id)
},
filename: function (req, file, cb) {
x = file.originalname; //+path.extname(file.originalname);
cb(null,x);
}
});
var upload = multer({storage: storage});
This is the post request where files get submitted on click submit.
router.post(upload.array("FileUpload",12), function(req, res, next) {
//Here accessing the body datas.
})
So what I want is that, I want to create a folder first with the name of the ID generated which can be access from the req.body and then upload those files into that folder respectively.
But since I cannot access the body first before upload I am unable to create that respective folder directory. Is there any other way around which I can think of and implement this?
Updated Solution using fs-extra package.
const multer = require('multer');
let fs = require('fs-extra');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
fs.mkdirsSync('./public/files/'+ req.user.id + '/' + Id);
cb(null, './public/files/'+ req.user.id + '/' + Id)
},
filename: function (req, file, cb) {
x = file.originalname; //+path.extname(file.originalname);
cb(null,x);
}
});
var upload = multer({storage: storage});
This is the post request where files get submitted on click submit.
router.post(upload.array("FileUpload",12), function(req, res, next) {
//Here accessing the body datas.
})
you have to install first the fs-extra which will create folder
create seprate folder for multer like multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.array('images', 100);
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
in your routes import multerhelper file
const multerHelper = require("../helpers/multer_helper");
router.post(multerHelper , function(req, res, next) {
//Here accessing the body datas.
})

How can I upload a zip file using nodejs and extract it?

I want to upload a zip file into the server using node.So can any one help me to figure it out.
First upload your zip file using Multer:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
Then unzip it using unzipper module:
1) Install unzipper module
npm i unzipper
2) ExtractZip.js JavaScript
const unzipper = require('./unzip');
var fs = require('fs');
fs.createReadStream('path/to/archive.zip')
.pipe(unzipper.Parse())
.on('entry', function (entry) {
const fileName = entry.path;
const type = entry.type; // 'Directory' or 'File'
const size = entry.vars.uncompressedSize; // There is also compressedSize;
if (fileName === "this IS the file I'm looking for") {
entry.pipe(fs.createWriteStream('output/path'));
} else {
entry.autodrain();
}
});
// Source
Test:
c:\Samim>node ExtractZip.js
You can try multer
npm install --save multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })

Send Image to Server Nodejs

I want to pass an image from the app to the server. But when I open the picture folder, no image found. I think the image able to send to the server but cannot store the image to the picture folder. I hope you guys can help me solve this problem. Thank you in advance
Project Structure
|
|-db
|-node_modules
|-app.js
|-picture
|-routes
|-perkhidmatan_rumput
|-rumput.js
rumput.js
var router = require('express').Router();
var multer = require('multer');
var upload = multer({ storage: storage })
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null,'../../picture')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
router.post('/api/PostPemantauanPerkhidmatanPotingRumput/:zon/:syarikat/:alamat_syarikat/'+
':nama_penyelia/:taman/:bulan/:tahun/:masa/:timeAMPM/:pusingan/:status/:catatan/:state/'+
':entryOperator', upload.single('image'),(req,res,next) =>{
console.log(req.file)
})
destination :
cb(null,'../../../picture')
and filename will be :
let path = require('path');
cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
Able to solve the problem.
var router = require('express').Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null,'picture/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({ storage })

Set Upload Directory dynamically when uploading a file in NodeJs

I am a novice at NodeJS and I created a service to upload images to a shared location. However, I need to set the upload folder dynamically based on the user id: for e.g. the folder will be /uploads/{userid}/file.txt
I am not sure how to do it and I have been searching today with no luck.
The NodeJS service looks like:
var express = require('express')
var multer = require('multer')
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Uploads");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({ Storage: Storage })
var app = express()
app.post('/upload', upload.array('uploads[]', 12), function (req, res, next)
{
return res.end("Files uploaded sucessfully!.");
})
Thank you for the help.
Try this
app.use(multer({
dest: './uploads/',
"rename" : function (fieldname, filename, req, res) {
return path.join(fieldname, req.params.user_id+".txt");
}
})

Resources