How to display images stored in Mongodb using Node.Js - node.js

I need your help on displaying images stored in MongoDB using Node.JS and express framework.
I've successfully saved the image using this method:
var multer = require('multer');
//var upload = multer({ dest: 'public/Images/' });
var fs = require("fs");
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/Images/')
},
filename: function (req, file, cb) {
//cb(null, file.originalname + '-' + Date.now())
cb(null, Date.now() + '-' + file.originalname);
}
});
var upload = multer({storage: storage});
var user = require('../app/model/user');
app.post('/upload', upload.single('meme'), function (req, res, next) {
if (req.file){
var host = req.hostname;
var filePath = req.protocol + "://" + host + '/' + 'public/Images/' + req.file.originalname;
//console.log(filePath);
var newMeme = new user();
newMeme.meme.imgs = filePath;
newMeme.uploadDate = Date.now();
newMeme.save(function (err) {
if (err)
throw err;
//console('Meme saved');
});
return res.send({
success: true
}) ;
} else {
console.log('failed');
res.send({
success: false
});
}
})
I'm now lost when it comes to displaying the images stored.
These are the stuff I want to display:
please, can someone help? I'm using express JS and ejs as my view engine.
Thanks.

Related

req.body not working when using multipart/form-data in html form NodeJs/Express

I am using body-parser to get info requested from forms, but when I put enctype="multipart/form-data" in the header of the form, the req.body will not working at all.
However, I have used multer lib in order to upload images as follow:
app.post("/", function (req, res, next) {
var button = req.body.button_name;
if (button == "upload") {
var UserId = 2;
var imageUploadedLimited = 3;
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var dir = "./public/images/uploads/";
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
dir = "./public/images/uploads/" + UserId;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
callback(null, dir);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now() + ".jpg");
},
});
const maxSize = 1 * 1000 * 1000;
var upload = multer({
storage: storage,
limits: { fileSize: maxSize },
fileFilter: function (req, file, cb) {
var filetypes = /jpeg|jpg|png/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(
path.extname(file.originalname).toLowerCase()
);
if (mimetype && extname) {
return cb(null, true);
}
cb(
"Error: File upload only supports the " +
"following filetypes - " +
filetypes
);
},
}).array("filename2", imageUploadedLimited);
upload(req, res, function (err) {
if (err) {
res.send(err);
} else {
res.send("Success, Image uploaded!");
}
});
}
});
If I print out the button variable from the second line, will show me undefined value. I know body-parser does not support enctype="multipart/form-data". In this case, how I can see the value from the form?
If you are using multer, it needs to be passed as middleware
// Do Something like this
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'Your path here')
},
filename: function (req, file, cb) {
cb(null, "fileName")
}
})
var upload = multer({
storage: storage,
})
app.post("/" ,upload.any(), function (req, res, next) {
// NOW YOU CAN ACCESS REQ BODY HERE
});

upload a xls file with postman to a RESTapi made with node/express

In node a can make something like this with and excel file in my directory.
app.post('/api/xlstojson', function(req, res) {
var workbook = XLSX.readFile('tc2.xls');
var sheet_name_list = workbook.SheetNames;
res.json(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]));
});
I want to test file uploading with postman. There I select POST, form-data, in key I select file instead of text and then in value I upload the tc2.xls file.
In my code I have something like this
app.post('/api/xlstojson', function(req, res) {
var workbook = XLSX.readFile(req.body.file);
var sheet_name_list = workbook.SheetNames;
res.json(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]));
});
But I get TypeError: path must be a string or Buffer. How should I modify my code to make this work?
Update:
I have been trying with multer, but the file does not appear in the folder
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
TypeError: path must be a string or Buffer
You're getting this error because you're not passing the file location. For this to work, you need to pass the location of the file within the upload/ folder
'use strict';
const XLSX = require('xlsx');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
}
});
var upload = multer({ //multer settings
storage: storage
});
function validate(req, res, next) {
if (!req.file) {
return res.send({
errors: {
message: 'file cant be empty'
}
});
}
next();
}
app.post('/api/xlstojson', upload.single('file'), validate, function (req, res) {
const fileLocation = req.file.path;
console.log(fileLocation); // logs uploads/file-1541675389394.xls
var workbook = XLSX.readFile(fileLocation);
var sheet_name_list = workbook.SheetNames;
return res.json({
json: XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]])
});
});
You need to upload the xls file from postman

Image Upload using nodejs

I am using Ionic v3 and and for backend used Nodejs.
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
});
var upload = multer({storage: storage});
To call this method we require req ,res through API call like below,
upload(req, res, function(err) {
res.end('File is uploaded')
});
My question that is it possible to call this upload function without API call(req,res) ? If yes how can we do ?
What i want to do is, I am developing chat application using ionic2 and nodejs where i can share image. That image should be upload to server side. How can I do for socket programming ?
If you want to upload image using base64 then you can use following code
socket.on('Upload_Image_base64', function(data)
{
var fs = require('fs');
var img = data.image64;
var imgname = new Date().getTime().toString();
imgname = data.userid + imgname + '.png';
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(__dirname + "/uploads/" +imgname, buf);
});
// here data.image64 and data.userid --> is the parameter which we pass during socket event request.
For multi part - this may help you.
socket.on('Upload_Image', function(data)
{
var app = require('express')();
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage }).single(data.file);
console.log(data.file);
app.post('/', function (req, res)
{
upload(req,res,function(req,res)
{
if(err)
{
console.log("error uploading file");
}
else
{
console.log("uploaded");
}
});
});
});

nodejs how to upload image from API

I am new to node JS and i have made function for uploading image from API.
But when i hit the URL from postman using form-data having field name image then in response it shows me.
Here is the postman image
Error uploading file
below is my code
My router.js contain:-
var express = require('express');
var router = express.Router();
var ctrlSteuern = require('../controllers/steuern.controllers.js');
router
.route('/steuern/image_upload')
.post(ctrlSteuern.imageUpload);
in Controller i have:-
var multer = require('multer');
var multiparty = require('multiparty');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './image');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('image');
module.exports.imageUpload = function(req, res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
return res.end("File is uploaded");
});
}
Here is my code for saving image to folder.
exports.saveMedia = (req, res) => {
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, (config.const.path.base + config.const.path.productReviewMedia));
},
filename: (req, file, callback) => {
callback(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({storage: storage}).any('file');
upload(req, res, (err) => {
if (err) {
return res.status(400).send({
message: helper.getErrorMessage(err)
});
}
let results = req.files.map((file) => {
return {
mediaName: file.filename,
origMediaName: file.originalname,
mediaSource: 'http://' + req.headers.host + config.const.path.productReviewMedia + file.filename
}
});
res.status(200).json(results);
});
}
Here is post man request.

File upload using MeteorJS?

(Cross post from the Meteor forums)
Say I wanted to upload a file to a server that is built with Meteor from another computer through HTTP when the second computer hits a certain API.
So far, I've been able to create such an application using NodeJS, the Express framework, and multer middlewear. I thought it would be easy to move that to Meteor.
NodeJS:
var express = require('express');
var multer = require('multer');
var done = false;
var port = 8888;
var app = express();
//Multer configuration
app.use(multer({
dest: './uploads/',
limits: {
fileSize: undefined
},
rename: function(fieldName, fileName){
return fieldName + Date.now();
},
onFileUploadStart: function(file){
console.log(file.originalname + ' has started downloading!');
},
onFileUploadComplete: function(file){
console.log(file.fieldname + ' has been uploaded to ' + file.path);
done = true;
},
onFileSizeLimit: function(file){
console.log("File " + file.originalname + " is too large");
},
onError: function(){
console.log("ERROR!!");
}
}));
// POST /api/upload
app.post('/api/upload', function(req, res){
if(done === true){
console.log(req.files);
done = false;
}
res.write("Ack!");
res.end();
});
app.listen(port);
However, when I tried to translate the app to Meteor, files were just not uploaded.
MeteorJS
var multer = Npm.require('multer');
var done = false;
//Set up Multer
Picker.middleware(multer({
dest: './fileUploads',
limits: {
fileSize: undefined
},
rename: function(fieldName, fileName){
return fieldName + Date.now();
},
onFileUploadStart: function(file){
console.log("[.]" + file.originalname + " upload has started at " + Date.now());
},
onFileUploadComplete: function(file){
console.log("[.]" + file.originalname + " upload has finished at " + Date.now());
done = true;
},
onFileSizeLimit: function(file){
console.log("[.]" + file.originalname + " file size limit has been reached");
},
onError: function(){
console.log("[.]ERROR!");
}
}));
var postPicker = Picker.filter(function(req, res){
return req.method === "POST";
});
//Actual route, after the middleware has been set up
postPicker.route('/api/upload', function(params, req, res, next){
if(done === true){
console.log(req.files);
done = false;
}
res.write("Ack!");
res.end();
})
When a call is made to the Meteor server, nothing happens. There is no error, and the server does not print anything. However, the caller receives the "Ack!" from the server.
This has me a bit baffled, and I will appreciate any and all help.
Is there a better way of doing this?
Thank you!
FS.Utility.eachFile(event, function(file){
var doc = new FS.File(file);
doc.metadata = {};
_.extend(doc.metadata, {
userId: userId
});
Images.insert(doc, function(err, fileObj){
})
})

Resources