How to save images to mongodb using multer.fields()? - node.js

I am getting a no file or directory error when trying to save my uploaded files to mongodb. I have uploaded with Multer, can anyone help me on how i can solve this issue?
this the error i am getting
this is the code (in the image) which is saving the images
i was expecting to save the image to mongodb.. however though, once before i used multer.single() it worked
but now with multer.fields() it is not working
below is the code i once used with multer.single()
productImage: {
data: fs.readFileSync("./public/" + req.file.filename),
contentType: "image/jpg"
},
please help.

Related

I'm trying to store the image inside the uploads folder. But still it is giving the same error

Screenshot of the error:
I'm trying to store the image inside the uploads folder.
As you guys can see I have configured the multer as well.
But still it is giving the same error.
Can anyone suggest please?
Remove the backslash after uploads in the destination i.e ('/uploads')
Based on your code, i saw that you're using diskStorage setting with destination field.
destination is used to determine within which folder the uploaded files should be stored. This can also be given as a string (e.g. '/tmp/uploads'). If no destination is given, the operating system's default directory for temporary files is used.
Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.
You can solve this by putting the following block of code before multer
fs.mkdir('./uploads', { recursive: true }, (err) => {
if (err) throw err;
});

Load images from local directory in Fabric

I am trying to load images from a local folder using fabric.js in node.
There seems to be very little up to date documentation on how to do this.
Most example use fabric.Image.fromURL(imageurl)
As far as I'm aware, this only works for web urls, not local paths.
Correct me if I'm wrong, but I have tried
fabric.Image.fromURL(imgpath, (img) => {
...
}
which throws the error Coul not load img: /image/path/img.jpg
Where
fs.readFile(imagepath, (err, i) => {
...
})
will successfully read the file, i will be a buffer.
What is the correct way to load a local image.
I know there is a fabric.Image.fromObject but I have no idea what type of object it wants.
I am currently loading the image into a 2d canvas object, converting it with canvas.toDataURL() and putting that url into fabric.Image.fromURL() which works but converting the image to a url is very slow due to large images. There must be a way to load the image directly and avoid this problem.
If you are using fabricjs 3+, that uses the new jsdom, you can use the file urls!
fabric.Image.fromURL(file://${__dirname}${filepath});
Check here on the fabricJS codebase how they handle reading files in browser and node for the visual test images
https://github.com/fabricjs/fabric.js/blob/master/test/lib/visualTestLoop.js#L139
try this one:
fabric.Image.fromURL(require("../../assets/mockup/100.png"), (img) => {...}

Save a partial video file locally using NodeJS

I have a serverless web application that is deployed on AWS and I have to take a screenshot from an uploaded video to S3. I am using ffmpeg to extract the screenshot but the only drawback is that I have to download the video file first in order to let ffmpeg work with it.
Knowing the fact I am using AWS Lambda and I don't have limits for video length users might upload large files which makes AWS Lambda to hit the storage limit.
To overcome this I thought of downloading a small chunk of the video and use it with ffmpeg to extract the thumbnail so using the S3.getOjbect method with range params I was able to download a chunk of the file but ffmpeg couldn't understand it.
Here is my code:
s3.getObject({
Bucket: bucketName,
Key: key,
Range: 'bytes=0-1048576'
}, (err, data) => {
fs.writeFile(fileName, data.Body, error => {
if (error)
console.log(error)
else
console.log('File saved');
})
})
And the code to extract the thumbnail:
const ffmpeg = require('fluent-ffmpeg');
new ffmpeg(fileName).screenshots({
timestamps: [0],
filename: 'thumb.png',
folder: '.'
})
And I am getting this error from ffmpeg
Error: ffmpeg exited with code 1: ./test.mp4: Invalid data found when processing input
I know there is a problem in saving the file like this but I couldn't find any solution that solves my problem. If anybody has one that would be much appreciated.
UPDATE:
It turns out that ffmpeg does this for me, I just gave it the url and it downloaded what it needs to render the screenshot without the need to download the file locally and the code looks like this:
const ffmpeg = require('fluent-ffmpeg');
new ffmpeg(url).screenshots({
timestamps: [0],
filename: 'thumb.png',
folder: '.'
})
To do that you would need to understand the format of mp4 and make sure you are fetching enough data to line up along a frame boundary, and then alter any headers so that ffmpeg can understand the partial data and doesn't think it just has a corrupted file.
While you're inside the AWS ecosystem you could try using Elastic Transcode to transcode the video and ask it to generate a thumbnail?
http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/preset-settings.html#preset-settings-thumbnails

How to list all the images/videos within a folder from cloudinary in Node.js?

I'm a newbie to Node.js. I've started building an app by cloning the cloudinary sample project from github. Then I changed my working directory to photo_album and installed all the dependencies required for the app. And then, I did some changes as per my requirements and made it image and video gallery app. 1. When I try to list all the images within a folder named my_photos something like cloudinary support
cloudinary.api.resources(function(result){console.log(result)}, { type: 'upload', prefix: 'my_photos/' }); Then, I'm getting this error
/home/fw66/WebstormProjects/cloudinary_npm/samples/photo_album/node_modules/cloudinary/lib/utils.js:1023
return callback(void 0, result);
^
TypeError: object is not a function
at /home/fw66/WebstormProjects/cloudinary_npm/samples/photo_album/node_modules/cloudinary/lib/utils.js:1023:18
at IncomingMessage. (/home/fw66/WebstormProjects/cloudinary_npm/samples/photo_album/node_modules/cloudinary/lib/api.js:103:51)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:944:16
at process._tickCallback (node.js:458:13)
Process finished with exit code 8 But when I try something like the following, Then, I'm getting the list of all the uploaded images irrespective of the specified folder.
cloudinary.api.resources().then(function(result){console.log(result)}, { type: 'upload', prefix: 'my_photos/' }); But I need only and only those images which are uploaded inside the folder mentioned above, not outside of it. So, How do I do that? 2. When I try to list all the videos within a folder named my_videos something like the following
cloudinary.api.resources(function(result){console.log(result)}, { resource_type: 'video', prefix: 'my_videos/' });
Then, I'm getting the same error as I did for images above. And when I try something like the following, Then, I'm getting the list of all the uploaded images instead of videos in the api response.
cloudinary.api.resources().then(function(result){console.log(result)}, { resource_type: 'video', prefix: 'my_videos/' }); I'm not sure what is wrong with my code. Please help me out here. Thank you!
I assume you're using the cloudinary is defined using require('cloudinary').v2 and in that case you should be using a bit different syntax.
Essentially, the callback function should come last and be receiving both error and result parameters. Also, note that once you provide a parameter hash, a type must be provided as well. For example:
cloudinary.api.resources({type:"upload",prefix:"my_photos/"}, function(error, result){console.log(error, result)})

Storing a image in mongodb

I'm trying to store images in mongo after downloading it with request
here is my code which causes a corrupted image to be stored in db.
request('http://test.jpg', function (error, response, image) {
db.images.insert(
{
file_name: 'test.jpg',
image: new Buffer(image)
},
function(err){
//mongojs callback
}
);
});
Please note I am using mongojs module and storing the images in regular document as BinData type.
Also if I write the image to a file, read it then save the image to the database then there is no corruption. But I don't want to do this as is my intention to avoid the file-system altogether.
I'm pretty this has something to do with encoding or buffers but I don't know enough about these to solve my problem.
If you don't want to use a proper image storing solution like gridfs you could base64 encode your images.
How can you encode a string to Base64 in JavaScript?
That gives you a string that you can store in mongo.

Resources