how to read image stored in mongodb and display in nodejs - node.js

I am making a nodejs app which displays pictures stored on servers ,I was using multer to store pictures in the same directory and I was using mongodb as my database to store the path of the picture that user uploads , and then i read the path and displayed the pictures something like this,
<div class="post-image flex">
<%var imagesource='../'+postobj.blob.path%>
<div>
<img class='onbottomimage' src="<%=imagesource%>" >
</div>
</div>
everything was working fine locally.
but now I have deployed my app to heroku and found out I cannot store pictures on heroku as the user uploads them, I still have the pictures stored in mongodb in base 64 format something like this
image
:
Binary('/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+EUI0V4aWYAAE1NACoAAAAIAAcBMgACAAAAFAAAAGIBOwACAAAA...', 0)
how do i convert them back to pictures and display them in img tag in ejs, or what other options do i have ,I dont want to change heroku but still be able to display the pictures that the user uploads.

If you are storing your uploaded images in the Heroku server, it is an utter waste. Because Heroku Dyno will restart every day which will delete all the extra added data other than data stored during deployment time.
I think you are using express.
let fs=require("fs")
let yourBuffer=//retrieve that buffer and store into this(yourBuffer) variable
let buffer = new Buffer.from(yourBuffer)
fs.writeFile(`location to storeimage/imagename.yourimageextension`, buffer, "binary", function (err, written) {
if (err) console.log(err);
else {
console.log("Successfully written");
res.sendFile((__dirname + `location of image/imagename.yourimageextension`))
}
});

I think a better solution would be using a 3rd party storage provider, aws s3 for example, and only store image url in the database

Related

Files stored to public folder get reset node js

In my node js application I am turning user data entered through a form into a js object and then storing that js object as a json file in the public folder of my ejs server. This works all well locally on my computer however when I use Heroku all the files that get stored into the server from form requests reset after a while.
Below is what I'm going to store json files
fs.writeFile(
__dirname + "/public/" + "AddonPosts/" + addonFromFile.name + ".json",
JSON.stringify(addonFromFile),
function (err) {
if (err) throw err;
}
);
Is there any way to write to my server without it constantly resetting? Additionally would there be an easy way to then download that folder I have written to?
Thanks
heroku Free tier does not save the files that are uploaded/Newly Created when your app is running. It resets your app to the stage how it was uploaded.
In short, dynamic uploads/Saving are not possible.
Alternative way: Use mongodb atalas[Free 500mb] to store your data

Send multiple images from node js to frontend

I am implementing a gallery where i wanted to show all images in a page - Reactjs or Angular
How can i send multiple images to frontend from NODE? I was able to send one image file saved in a folder in nodejs.
Below is the code for sending single image - im able to see that image using POSTMAN
Note : here im fetching the image name from a table - These images are there in event folder(image1.jpg, image2.jpg...)
console.log(req.files);
const {id} = req.params;
var sql = "SELECT image from users_image where id = ?";
var query = db.query(sql, [id], function(err, result) {
if(err){
console.log("Error ", err);
res.status(500).send(err)
} else {
const fileNameAndPath = result[0].image; //image1.jpg
if(err) res.status(500).send(err);
res.sendFile(fileNameAndPath, { root: './public/images/upload_images/event' })
}
});
}
But im not able to send multiple images using sendFile() as it does only single image.
How can i implement this?
is it possible to get the preview using postman if i sent multiple images from node?
I could find many example which reads images from server but to html files in same backend directory. They are not sending the response to frontend, so that we can get the image and show in out ui built in react or angular.
Is my approach correct? Planning to deploy frontend, backend and DB in same server
If I understood correctly, your images are in a folder that is located in your NODE JS backend folder and you want to send multiple images depending on request from your REACT Side.
To do this you can make the folder where you stored those images in backend as a public static folder.
In your entry point of Node Application,
app.use(express.static(__dirname+'/<foldername>'));
Now suppose you have a image inside the folder named flower.jpg, car.png and jolly.jpg that you want to send.
The URL for these images will be :
localhost:<port number>/<image name>
For example :
localhost:3000/car.png
localhost:3000/flower.jpg
Now to access from your react code all you need to do is, replace localhost with the IP of your NodeJS Server.
Something like : 172.32.112.12:3000/car.png
You just need to make sure that the image names are not something common and easy.
My image names are something like 1639873167172-464191690.jpg. I change it while I store it on database.
If the photos are already hosted on your server, you should send an array of urls to the photos. In the frontend, you can loop through the array of urls and display the images using image tags.

how to read the attachments stored using multer - nodejs/expressjs

I am new to node programming, I am trying to build an app which will be having a feature where users will be uploading there docs/images and then afterwards they can also view the same files which they had uploaded earlier.
I came across multer with which I built an API which stores the attached file on the server, please refer below code :
app.post('/submit-form', uploadPlugin.single('files'),(req, res) => {
console.log(req.file);
if (!req.file){
res.status(400).json({"error":"Something went wrong while uploading file"})
return;
}
else
{
path = "C:\\Users\\APIs" + req.file.path
console.log(path)
res.sendFile(path);
}
})
Now my problem is if at all I need to view the attached files, how can I do so (For ex: if someone uploads an Image it should show this image was uploaded)
I am trying to send the file as the response but in the HTML page it just shows gibberish (probably the byte stream, refer the image attached) instead it should display the actual document say image for example.

How to upload multiple files in React-Redux

I had a query that I wanted to ask you about. I was building an application in React-Redux with Express NodeJS as backend, and postgreSQL as db. I wanted to implement a File Upload component into it. Can you please tell me how should I do that ?
Our team had previously implemented file upload in angular using multer on the backend. When we did the same in redux the small files get uploaded fine but when I try to upload a file over 4 mb it re-renders the page before the file is completely uploaded.
Please guide me how should I do this ? If you have a code sample that I can understand, that will also be great.
It is possible to upload multiple files at once in React.
<input type="file" multiple
name="myImage" accept=".png, .jpeg" className="multiple-upload"
onChange={this.uploadScreenshotFile} />
Here is uploadScreenshotFile function
uploadScreenshotFile(event){
for(let size=0; size < event.target.files.length; size++){
console.log('Selected file:', event.target.files[size]);
let file = event.target.files[size];
console.log("uploading screenshot file...");
// Do necessary request to upload here.......
}
}

Displaying private S3 images in node express app

I am developing a node express web application and I am trying to figure out how to display private s3 images when performing a query or single request for an image to views for proper html rendering. I've looked around and didn't find enough information to fully wrap my head around this.
To reiterate, I cannot publicly host them. They have to be privately stored and retrieved when a user uses my express app. I've tried knox which is great for piping, but I don't know how to display all images in one go to a query results page for example. Or more importantly, how to show the raw image data recieved from knox. I also read some stuff about Amazon CloudFront and all that stuff, but would like to exhaust some closer options than doing more and more configuration.
So, how can I view these private s3 images from an express web app? More specifically, displaying a collection of images or a single image.
So if your goal is to have the server fetch the images and then send them to the client, it looks like knox should be able to help you:
from their Github page, with tweaks:
app.get('/img/:filename', function(req, res){
client.getFile('/whatever/' + req.query.filename, function(err, s3res){
s3res.pipe(res)
});
}
Note: untested.

Resources