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.
Related
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
i have a mern application in which a person can upload his profile pic. Now once the main page of the app loads i want to show all the users along with their profile picture and a little info. For this to happen the server must return multiple images. How do i achieve this in node js. Sending multiple images to the frontend.
You can send it to the front-end as a JSON response.
Since you didn't provide any code to start with, I assume you are using MongoDB with mongoose.
async function getUsers () {
try{
const data = await User.find()
const users = data.map((user)=> user)
res.json({
users
})
}catch(err){
throw err
}
The piece of code above returns a JSON response with an array of the user objects if, in your database there an image field, you will get it also in the JSON response while fetching it on the front-end.
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
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.
I am working on an application using Angular 5 as a front-end and Node.js as a back-end which uploads images to the server.
The problem is that after I upload an image to the server I cannot display it in angular.
My folder structure is like this:
AppName/client/src/app/app.component.html <- Here I want to display
the images; AppName/server/public/images <- Is the place
where the images are stored
Does anyone have any idee?
You have to configure your server in order to serve the right image when required. The problem is not about Angular.
If you are using express, you can add the following rule before serving the webapp:
app.use(express.static('server/public/images'));
Fix the above code with your relative path.
In this way, when your web server will receive a request, he will firsty see if it's an image contained in your folder, otherwise it will serve Angular.
Note
In this way, if you try accessing a not existent image, you will receive a text/HTML result with your webpage as content and 200 as status code.
You may need checking the extension of the file, if it is jpg, jpeg, png or gif you search in the folder, if the image exists you send it as response and if it doesn't exist you send 404 status code.
If the extension is not one of the above, then you serve the webapp in any case.
app.use(express.static('server/public/images'));
app.get(/\.(jpg|jpeg|png|gif)$/, function(req, res) {
res.status(404).send('Not found');
});