Multer upload an image to node js server (Github as storage) - node.js

I deployed a web based application but the multer upload doesn't work. It does work in localhost there is no error but the file/s are not save in my director. Here is my code:
const multer = require("multer");
const imageFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Please upload only images.", false);
}
};
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/resources/static/assets/uploads/");
},
filename: (req, file, cb) => {
cb(null, `${file.originalname}`);
},
});
var uploadFile = multer({ storage: storage, fileFilter: imageFilter });
module.exports = uploadFile;

What happen is the __basedir expression will cause "Uncaught ReferenceError: __basedir is not defined" error, but it's silently eaten in the code. To get the error to properly propagate, try adding try-catch block around the offending line this:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
try {
cb(null, __basedir + "/resources/static/assets/uploads/");
} catch (e) {
cb(e);
}
},
filename: (req, file, cb) => {
cb(null, `${file.originalname}`);
}
});

Related

multer node js upload image

when i send a new image the link apper like this:
uploads\854645135.jpg
i want to change this antislash"" to slash"/"
cause i can't find this data in frontend
const uploadRouter = express.Router();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
cb(null, `${Date.now()}.jpg`);
},
});
const upload = multer({ storage });
uploadRouter.post('/',isAuth, upload.single('image'), (req, res) => {
res.send(`/${req.file.path}`);
});

Uploading file using multer triggers process.on('SIGINT')

When I upload file using multer nodemon restarts web server. It's fine on my local machine which is windows. It only happens when I start my server on ubuntu machine. What's the problem? My code is here below.
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../public/uploads/'))
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb('Only images! jpeg|jpg|png|gif ');
}
}
const upload = multer({
storage: storage,
limits: { fileSize: 5242880 },
fileFilter: function (_req, file, cb) {
checkFileType(file, cb);
}
});
router.route('/upload').post(protect, upload.array('banner', 12), (req, res, next) => {
console.log(req.files)
if (!req.files) {
res.status(400).json({ success: false, message: 'File not found' });
return;
}
const data = [];
const baseUrl = `THE_URL_FILE_UPLOAD`;
req.files.map((file, idx) => {
data.push({ path: baseUrl + file.originalname })
})
res.status(200).json({ success: true, data })
});

post multiple field of file upload in different folder in node js api using multer

I am using multer for single file upload in 1 post field but what if i want to add 2 or more file inside different post field like below.
this is for different module.
so for single file upload i am using following code
var uploadfilename = "";
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './public/assets' + customStrings.FOLDER)
},
filename: (req, file, cb) => {
uploadfilename = Date.now() +
path.extname(file.originalname);
cb(null, uploadfilename);
}
});
var upload = multer({
storage: storage
});
and in post api route
router.post("/news", upload.single('image'), (req, res) => {
});
now if i want multiple field for file upload what we will do ??
i fount one solution for that is following
var uploadfilename = "";
var uploadCityfilename = "";
var storage = multer.diskStorage({
destination: (req, file, cb) => {
if (file.fieldname == "image") {
cb(null, './public/assets' + customStrings.FOLDER)
} else {
cb(null, './public/assets' + customStrings.CITY_FOLDER)
}
},
filename: (req, file, cb) => {
if (file.fieldname == "image") {
uploadfilename = Date.now() + "-" +
customStrings.IMAGE_POST_NAME + path.extname(file.originalname);
cb(null, uploadfilename);
} else {
uploadCityfilename = req.body.city + path.extname(file.originalname);
cb(null, uploadCityfilename);
}
}
});
var upload = multer({
storage: storage
});
and in post api route
router.post("/imageupload", upload.any(), (req, res) => {
});
it works for me :)

Double backslash into path

I have using this the tuttorial of Academind how to load image using multer into node JavaScript rest service.
About path destination folder I use this code:
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
But the path generated have double backslash that show as one backslash:
uploads\2018-09-16T13-02-45.535Z1536685465dummy4.jpg
How I can replace destination path with slash?
i had the same issue, and since i didn't find anything i did this as a work around
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
cb(null, `${new Date().toISOString().replace(/:/g, '-')}${file.originalname.split(" ").join("_")}`);
}
});
const user= new User({
_id : new mongoose.Types.ObjectId(),
name : req.body.name,
image: req.file.destination + req.file.filename,
});

Same Image not uploading in express

I am trying to upload an image using express but I am facing two problems, first, whenever I upload the same image again it's not getting uploaded and secondly after uploading any single image a file with image also uploading. Here is my code.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
var file = __dirname +"/images" + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err,data) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
The uploads.single("file") middleware Will handle the file upload. You don't have to specifically fs.read and fs.write the file.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
EDIT: The above code will upload the file with hex string as filename without any extension.
In order to add rename function you need to use diskStorage. Here is the code taken from this github issue page.
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype)); //this is the rename func
});
}
});
var uploads = multer({ storage: storage });
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
Now you can use the uploads variable as middleware as shown in the above snippet.
you can edit the filename: function (req, file, cb) { .. } according to your needs. Now the filename will be, <16characterhexstring>.ext
another way to handle it will be not using middleware and using multer manually with below options :
try {
var storage = multer.diskStorage({
destination: function(request, file, callback) {
//define folder here by fs.mkdirSync(anyDirName);
},
filename: function(req, file, callback) {
callback(null, anyFileName);
},
limits: self.limits
});
var upload = multer({
storage: storage,
fileFilter: function(request, file, callback) {
// here you can filter out what not to upload..
}
}).any();
upload(request, response, callback);
} catch (e) {
}
hope this helps!

Resources