Storing and downloading pdf files from mongoDB using Node.js - node.js

I am using NodeJs, mongoose, ejs
I want the user to be able to upload his CV (Less the 16 MB) as a pdf file, then the admin to be able to download the pdf or view the CV on the website.
I did the upload part where I stored the cv like this in the database (which might be a wrong way):
cv: Object {
fileName: "Test Results All in testing-homework.pdf"
filePath: "cvs\1650985306448-.pdf"
fileType: "application/pdf"
}
and the pdf file is stored in the "/cvs" folder after upload.
I'm seeking a way to be able to download/view the pdf file from the database.

I will suggest you to use GridFs from mongodb.
refer:https://www.mongodb.com/docs/drivers/node/current/fundamentals/gridfs/
To Download from DB
bucket.openDownloadStreamByName('your_file_name').
pipe(fs.createWriteStream('./desired_name_of_output_file'));
Some of the Basic Upload and Download Operations using GridFs in MongoDB
const mongoUrl='mongodb://127.0.0.1:27017/db'
const mongodb = require('mongodb');
const fs = require('node:fs');
const client = new mongodb.MongoClient(mongoUrl)
const db = client.db('db');
Create Bucket with user-defined name
const bucket = new mongodb.GridFSBucket(db,{bucketName:'name_of_bucket' });
Upload to DB
fs.createReadStream('./filename.pdf').
pipe(bucket.openUploadStream('filename', {
chunkSizeBytes: 1048576,
metadata: { field: 'filename', value: 'myValue' }
}))
Find
const cursor = bucket.find({});
cursor.forEach(doc => console.log(doc));
Delete
cursor.forEach(doc => bucket.delete(doc._id));

Related

How to upload video or image file to database

I am working in a project in which i need to create api using nodejs to upload video or image file to the postgres database
How i can do this
Thanks a lot
You can convert an image or video to base64, and then upload the base64 encoded string to your database.
const fs = require('fs');
function encode_base64(file) {
const bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');
}
const image = encode_base64('image.jpg');
const video = encode_base64('image.mp4');

jsPDF saving the file without extension when sent to nodejs/expressjs server

I have a class based react component that takes data from a user. The data is then fed to jsPDF.
let doc = new jsPDF();
doc.save()
This works fine. It saves the file with .pdf extension.
Now the problem is that I am sending this file to the express.js backend.
const pdf = new Blob([this.state.doc.output("blob")], {
type: "application/pdf",
});
OR
const pdf = this.state.doc.output("blob");
NODE.js
I am using Formidable.js for receiving the file.
const newPath = files.pdf.path;
The file gets saved without an extension.
I also did this
const newPath = `${files.pdf.path}.pdf`
This adds the .pdf to the string that is saved to mongodb, but the file saved is without any extension.
Solved.
https://github.com/node-formidable/formidable/issues/680
//front-end
const pdf = new File([doc.output("blob")], "myDoc.pdf", {
type: "application/pdf",
});
//Node
const newPath = files.pdf.path;
Thanks to https://github.com/GrosSacASac

Cutted photo off when is big one. Nodejs, express, graphql

When I upload a big photo then it's cut off. These are a few lines where I save the photo on the backend side. It happens only when a photo is big (more than 2MB). I use nodejs, express, graphql with apollo-upload-client. All is running on docker with nginx.
const { filename, createReadStream } = await input.photo;
if (isFunction(createReadStream)) {
const fileStream = createReadStream();
const trimedFilename = trim(filename);
fileStream.pipe(fs.createWriteStream(`${eventFolderPath}/${trimedFilename}`));
}
The photo looks like that:
corrupted photo

how to upload multiple files inside mongodb using nodejs

Hello friends I am new in nodejs and mongodb. Is it possible to upload multiple files inside single mongodb doc with other information.
You can make use of BSON (Binary JSON) to store files in MongoDB collections. However, BSON has a limit of 16MB. If you are planning to store files bigger than that, consider GridFS
You can write files to MongoDB like so in Node.js:
var Binary = require(‘mongodb’).Binary;
//Read the file that you want to store
var file_data = fs.readFileSync(file_path);
var db_doc = {};
db_doc.file_data= Binary(file_data);
var my_collection = db.collection(‘files’);
my_collection.insert(db_doc, function(err, result){
//more code..
....

MongoDB GridFS uploads zero-length file when using Node and request

I'm trying to save a file from a URL to a Mongo GridFS file. I'm using the request npm module, and the official mongo driver.
This is my code:
function retrieveAttachments(NormalizedMessage) {
NormalizedMessage.attachments.forEach(
function (currentAttachment) {
var bucket = new GridFSBucket(db);
var httpRequestStream = require('request');
httpRequestStream.get(currentAttachment.url)
.on('error', function (err) {
console.log(err);
})
.pipe(bucket.openUploadStream('dsa'));
}
);
}
"db" is obtained from MongoClient.connect, and GridFSBucket = require('mongodb').GridFSBucket;
The problem I have is that the file is inserted in mongo (I can see it in the fs.files collection), but it's length is zero.
If i also add a .on('finish') event to the upload stream, it gets called.
If I replace bucket.openUploadStream('dsa') with fs.createWriteStream('someFile'), the HTTP request is saved to someFile in the local filesystem.
If I replace httpRequestStream.get(currentAttachment.url) with fs.createReadStream("test.jpg"), the file test.jpg is successfully uploaded to GridFS.

Resources