Insert an image in mongodb using GridFS - node.js

i am trying to upload a image in mongoose collection using nodejs & express, first i tried in uploading in temporary folder it's works perfectly. but inserting in to mongoose collection using GridFS query is difficult to me, i familiar to creating schema and insert query. please guide me.
here i giving my server side code for how i uploading file to temporary folder.
exports.uploadimg = function(req, res){
console.log("c1",req.files);
console.log("c2",req.files.uploaded_file.originalFilename);
console.log("c3",req.files.uploaded_file.path);
fs.readFile(req.files.uploaded_file.path, function (err, data){
var dirname = "/home/Mel/www/2013/img-folder";
var newPath = dirname + "/classes/" + req.files.uploaded_file.originalFilename;
fs.writeFile(newPath, data, function (err) {
if(err){
res.json({'response':"Error"});
}else {
res.json({'response':"Saved"});
}
});
});

Please checkout following link to find out solution of this question
Storing data stream from POST request in GridFS, express, mongoDB, node.js
Thanks

Related

How to display images from mongoDB gridfs in react/html?

I'm new to NodeJS and express and recently figured out how to save images in mongodb with the gridfs system and mongo native nodejs driver. Now, I want to display the images I downloaded from mongo gridfs. I tried two methods:
//getProfilePicture route function
exports.getPfp = async function(req, res, next){
//retrieve user from auth middleware with mongoose
const user = await User.findOne({uniqueID: req.user.uniqueID});
const profilePicture = user.profile.profilePicture[0];
//profilePicture.payload is the filename with which the file in the fs.files collection is saved
console.log(profilePicture.payload)
if(profilePicture.type='pfpUploadSubmit')
{ client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("BookProject");
const bucket = new mongodb.GridFSBucket(db);
const dlpath=path.join(__dirname, '../public/image.jpeg')
//here im writing the file from gridfs to a local node directory
bucket.openDownloadStreamByName(profilePicture.payload).
pipe(fs.createWriteStream(dlpath)).
on('error', function(error) {
assert.ifError(error);
}).
on('finish', function() {
console.log('done!');
process.exit(0);
})
})
}
}
Another method is instead of the
.pipe(fs.createWriteStream(dlpath))
I simply write
.pipe(res)
the former succesfully save the image on my nodeJS local directory, but how do I allow reactjs client to access it?
The the second sends the stream in the response object. When I console.log the response, I get what seems like an unreadable data stream and I have no idea how to turn it into an image to render onto my react component.
What is the best way to do this in production?
Thanks from a newbie

Node Cloudinary Picture Upload not Working in Heroku

I've created a SNS web application (using node.js) where people can upload pictures (using cloudinary) into collections.
The application works perfectly on a cloud-based IDE I use for writing code; however, after pushing it to heroku, the image upload no longer works. I don't get any error message in my console, even though I think it should be console.logging it, however the error flash happens and the image doesn't upload.
Here is my code:
router.post("/", middleware.isLoggedIn, upload.single('image'), function(req, res){
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if (err) {
//if error
console.log(err.message);
req.flash("error", "Can't upload image, try again later.");
return res.redirect("back");
}
//else
// add cloudinary url for the image to the campground object under image property
req.body.image = result.secure_url;
req.body.imageId = result.public_id;
// add author to campground
req.body.author = {
id: req.user._id,
username: req.user.username
};
I've tried searching other posts for a possible reason; but I can't find anything that matches my situation. If anyone can help...please, your advice would be greatly appreciated!
Thank you.
Sorry! The problem was the CLOUD_NAME config variable had '' marks around it.
If anyone is having similar issues, try removing the quotes around the name variable.

Node/Express/MongoDB app: uploading multiple images using Multer and Cloudinary

hope someone can help me with this:
I am working on a Node/Express/Mongo CRUD app where every post/document has ONE image. I am using multer and cloudinary for uploading the images. However, I want users to be able to upload multiple images to each post. Ideally, the image urls/paths and IDs would be stored in arrays in my database.
I have been trying and researching for hours now but cannot seem to make it work, and there is no tutorial out there explaining how this (simple) task can be achieved using multer and cloudinary.
This is the code I am using to upload ONE image per post, which is working:
// CREATE Route - add new post to DB
router.post("/", middleware.isLoggedIn, upload.single('image'), function(req, res) {
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if(err) {
req.flash('error', err.message);
return res.redirect('back');
};
// add cloudinary url for the image to the post object under image property
req.body.post.image = result.secure_url;
// add image's public_id to post object
req.body.post.imageId = result.public_id;
// add author to post
req.body.post.author = {
id: req.user._id,
username: req.user.username
}
Post.create(req.body.post, function(err, post) {
if (err) {
req.flash('error', err.message);
return res.redirect('back');
}
res.redirect('/posts/' + post.id);
});
});
});
How would I need to change this code in order to achieve this goal?
Thanks in advance for your help!
The upload API currently only supports a single file upload at a time, it does have a high concurrency rate (of about 40-50 concurrent calls) so you can use multi-threads to upload many files at once.
You can also use asynchronous calls, and tell Cloudinary to do the upload in the background by adding the async parameter and setting it to true.

Upload and Retrieve PDF file to PostgreSQL using Node.js, Express and Knex

I am trying to upload and retrieve a PDF file to and from a PostgreSQL Db using Node.js, Express and Knex.
The DB column documentfile is file type Bytea.
The file seems to be uploading to the DB and is returned. The resulting PDF file (test3.pdf) does not want to open. I have been struggling with this for a long time now. Any help will be greatly appreciated!
Node.js code to upload the file :
app.get('/uploadfile', (req,res) =>{
fs.readFile('0203.pdf' function(err, imgData) {
console.log(imgData)
knex('documenttable').insert(
{documentname: '0203.pdf',
documentfile: [imgData]
})
.then( function (result) {
res.end(console.log("Document uploaded To DB"));
});
});
});
Node.js code to retrieve the file:
app.get('/dbfileback', function(req, res, next) {
knex('documenttable').where({
documentnumber: '1'
}).select('documentname', 'documentfile')
.then( function (result) {
fs.writeFile('test3.pdf', result[0].documentfile,'binary');
res.end(console.log("Done"));
});
});

Uploading, storing and displaying image via nodejs and mongodb?

How do I create a web gallery and uploading, storing and displaying images via nodejs and mongodb?
I have tried to write some code myself, but don't manage to solve the problem.
Do someone have a link or tutorial that helps me solve the problem?
It is not recommended to store whole images on databases. It can be done but based on similar questions on stack overflow it is better to store images on your file system. That can be done by using themulterand fs module to handle the upload and store it on the file system. You can even use an image proccessor to confirm that what was uploaded was really an image and not something else. I recommend using the sharp module found on npm to do that. This way you are sure that nothing can go wrong and you can even resize images before storing. Here is some code for this using express.js:
var multer = require('multer');
var uploadPicture = multer({
dest: 'temp/'
});
var sharp = require('sharp');
app.post('/upload', uploadPicture.single('profileIcon'), function (req,res) {
fs.readFile(req.file.path, function (err, data) {
if (err) res.end('UNRESOLVABLE ERROR');
sharp(data).resize(200, 200).toFile('./photos/pic.jpg', function (err, info) {
//DELETE THE TEMPORAL FILE
fs.unlink(req.file.path, function (error) {
if (error) res.end('UNRESOLVABLE ERROR'); //CODE 3 ALARM
res.end('success');
});
}

Resources