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.
Related
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.
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
Im making a web app, using node.js, express.js and mongodb and trying get my contact form done. I would like site visitors to contact me via the form where they can put their name, email and message, along with an uploadable file image so they can show me what they want to be done as a sample through an image.
It seems like every websites have this functionailiry but I cant seem to find the answer Im looking for. Any help and guides would be appreciated.
i think you could use this library i've just found for uploading files with Javascript by using a file dialog: https://fineuploader.com/demos.
I think your issue is pretty much solved after that because for what concerns the form, you may easily create the input tags in HTML and then get data from them by using NodeJS.
To upload files you need to use a form-data handler. I use multer:
npm i multer
You upload a file like this:
const multer = require('multer')
const upload = multer({ dest: 'uploads' })
app.post('/profile', upload.single('image'), (req, res)) {
//Now the image is uploaded in uploads folder you just need to send it back
}
Note that image is a form's input name.
For infroamtion on how to send the image see this
Look also at the docs for multer
If you don't want to store image you can use then fs module to delete it.
I have created an App in Nodejs, this App involves users to upload some files such as profile pictures and some other media file, so these files are stored in certain folders here in my Web Application folder.
This works well locally now after deploying my App when the user do an upload these picture and other files it return an error, I suppose I should be maybe doing some configuration on Cloud Storage and let my App Engine Application be able to read and write to such folder using NodeJs. Please help me with how I can achieve this.
I use this following Code to create these files from Base64 data which is Uploaded using Rest API
var data = req.body.image; //base64 image data
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET); //decalre bucket
var blob = bucket.file('new_image.png');
writeScreenShot(blob, data);
blobStream.on('finish', () => {
res.send("Success");
});
blobStream.end(req.file.buffer);
function writeScreenShot(blob, data)
{
var strm = blob.createWriteStream();
strm.write(new Buffer(data, 'base64'));
strm.end();
}
This is how I implemented it so far, but it returns image that says it looks like we don't support this image type while file extension of this image is png, it seems like I have created this image wrongly now got affected the metadata of it. Thanks in advance
I'm on Windows 8.1 running node 10.22, express 4.11.2
I'm trying download a file from the Ziggeo API, but the resulting file comes out corrupt.
var express = require('express');
var app = express();
app.get('/download/:id',function(req,res){
downloadVideo(req.params.id,res);
});
function downloadVideo(id,res){
sdk.Videos.download_video(id,function(back){
fs.writeFile('downloadedVideo.mp4',back,function(err){
if(err){
console.log(err);
res.sendStatus(400);
}else{
res.sendStatus(200);
res.end();
}
});
});
}
The resulting file is corrupt and cannot be played.
When I download the same video using the Ziggeo dashboard, the filesize is bigger and I can play it back fine.
If I open the two files as text files and diff them, there are a few lines of similarities, but the files are largely different.
I've tried all three encoding types that writeFile takes as a parameter, but none of those help.
I also tried the Streams.download_video method, and that gives the same results.
Please try the updated SDK on GitHub:
https://github.com/Ziggeo/ZiggeoNodeSdk
Check the data that sdk.Videos.download_video passes to your callback. I expect that you are recieving JSON data (or some other data type), but are expecting a H.264 video. The Ziggeo API documentation states:
Whenever you interact with Server SDK, the Client API or Webhooks, you will receive resource objects from our system.
Try running file on your output video to identify what filetype you end up with
See The Ziggeo docs