Send Image to Server Nodejs - node.js

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 })

Related

Multer Doesn't Save Images in Local Folder

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"...

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 })

move and rename image after image upload in Multer

I've developed a small web server to upload pictures.
Now I would like to use the original name of the picture and move the picture into a folder. the name of the folder is in the req.body.
Ok, the upload works, but where is the point to rename oand move the picture?
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });
const app = express();
const PORT = 3000;
app.use(express.static('public'));
app.post('/upload', upload.single('image'), (req, res) => {
console.log(req.file.originalname)
console.log(req.body.foldername)
if (req.file) {
res.json(req.file);
}
else throw 'error';
});
app.listen(PORT, () => {
console.log('Listening at ' + PORT);
});
This is your question answer to rename a file before it upload
var storage = multer.diskStorage({
// Where to save
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
// File name
filename: function (req, file, cb) {
cb(null, file.originalname) // file.originalname will give the original name of the image which you have saved in your computer system
}
})
var upload = multer({ storage: 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