res.sendFile, res.download PDF File - node.js

I have currently a problem to fetch my pdf from the backend to the front-end.
I'm using NodeJS.
I have all my pdf made with Puppeteer and saved on a PDF directory.
I'm trying to fetch these PDF for the front-end. (for download)
I'have tried with res.sendFile and res.download (res.sendFile(path.join(__dirname,"/path"), res.download(path.join(__dirname,"/path))
This is the response from the front-end:
{data: "%PDF-1.4↵%����↵1 0 obj↵<</Creator (Chromium)↵/Prod…e 7↵/Root 6 0 R↵/Info 1 0 R>>↵startxref↵675↵%%EOF", status: 200,...}
I can't download this files.
Image
Code from back-end :
try {
res.download( path.join(__dirname, '/PDF/sofianddes.pdf'), (err) => {
if (err) {
console.log(err);
}
});
} catch (err) {}
Someone could help me ?
Thanks

Related

blank pdf file issue in node js

Hi everybody I am facing an issue where when I create and save pdf contents to a pdf file it always opens up blank here is my code snippet
i am using express.js
fs.writeFile(
"response.pdf",
pdfData.data,
{ encoding: "utf-8" },
function (err) {
if (err) throw err;
console.log("File is created successfully.");
}
); ```
here is an example of the pdf data I'm trying to add to the pdf
```%PDF-1.5
%����
3 0 obj
<</ColorSpace/DeviceRGB/Subtype/Image/Height 224/Filter/F...(more characters)````
please advice

Download .txt file stored on server using Hapi js

Folks, I am trying to create .txt file on submitting a form and storing it in /files folder. Then, onclick of Download button I should be able to download that file. I am using inert package from Hapi js to download the file. files folder is in root of the project.
This is my route handler for downloading
handler: async (req: Hapi.Request, h: Hapi.ResponseToolkit) => {
try {
const user = await prisma.user.findUnique({
where: {
id: Number(req.params.id)
}
});
if (user) {
h.file(`${__dirname}/../../files/certificate_2.txt`, {
mode: 'attachment',
filename: 'certificate_2.txt'
});
return h.redirect('/');
}
} catch (err) {
console.log(err);
}
But, I am not able to download the file on client side. Please help me to solve this issue

How do I create a file in express and node on my server and then download it to my client. I am using NextJS for my frontend and backend

How do I create a file in express and node on my server and then download it to my client. I am using NextJS for my frontend and backend. I am confused on how I would download the file on the front end after the file is created on the root of the server folder. Since I am using React for my frontend whenever I try to visit that filepath it tries to take me to a page instead of the file
Here is what I have in my express route in node
var xls = json2xls(json, {
fields
});
// If there isn't a folder called /temp in the
// root folder it creates one
if (!fs.existsSync('./temp')) {
fs.mkdirSync('./temp');
}
const fileName = `temp/${req.user.first_name}${req.body._id + Date.now()}.xlsx`
// fs.writeFileSync(fileName, xls, 'binary');
fs.writeFile(fileName, xls, 'binary', function (err, result) {
if (err) {
return console.log(err);
}
console.log(result, 'this is result')
});
Here is what I have on my frontend
axios.post('api/download',payload)
.then(res => {
const link = document.createElement('a');
link.href = res.data.url;
link.download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(err => {
throw err
})
Can you make request with GET on api, and.
Make request with GET.
Make temp directory to be static resources directory:
app.use(express.static('temp')); // app is your express instance.
// Maybe you have to correct temp's path
Response the post request with file url data
fs.writeFile(fileName, xls, 'binary', function (err, result) {
if (err) {
return console.log(err);
res.status(500).json({err});
}
console.log(result, 'this is result');
res.json({url: 'http://localhost:8080/temp/' + fileName}); // res is response object of you router handler.
// Maybe you have correct the server address
});
On other way, you can send the xls binary direct to client, in the client you create a BLOB object from the response, then create download link for the blob object.

Upload images into a file server and store the url to the image using nodejs

I am implementing a web app using MEAN Stack and Angular 6. There I want to submit a form with file upload. '.png' files should be uploaded.
I want to save the file in a different file server and send the url to the image.Currently I upload files into a folder in my project and save the image in db (I used ng2fileupload and multer for that.). Then it saves like this.
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAV4AAAFUCAYAAABssFR8AAAK..."
But I want to save the image url and the image should be retrived by the url. Does anyone can explain a proper method for that?
I faced the same problem a month ago and find out a solution to this problem. Though I haven't used multer in the app.
From my frontend, I will be sending an object to Node API endpoint /event which will look like:-
let img = {
content: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...",
filename: 'yourfile.png'
}
At the backend, I'm using Cloudinary to store my images (Its free plan allows 10GB storage) and returns secure https URLs. So install it using npm i cloudinary and require in your api.js file.
And add the below configuration
cloudinary.config({
cloud_name: 'yourapp',
api_key: 'YOUR_KEY',
api_secret: 'YOUR_SECRET_KEY'
});
Last Step:- (Not so optimized code)
Let say I have an event Schema which has images array, where I'll be storing the URLs returned by cloudinary.
app.post('/event', (req, res) => {
try {
if (req.body.images.length > 0) {
// Creating new Event instance
const event = new Event({
images: [],
});
// Looping over every image coming in the request object from frontend
req.body.images.forEach((img) => {
const base64Data = img.content.split(',')[1];
// Writing the images in upload folder for time being
fs.writeFileSync(`./uploads/${img.filename}`, base64Data, 'base64', (err) => {
if (err) {
throw err;
}
});
/* Now that image is saved in upload folder, Cloudnary picks
the image from upload folder and store it at their cloud space.*/
cloudinary.uploader.upload(`./uploads/${img.filename}`, async (result) => {
// Cloudnary returns id & URL of the image which is pushed into the event.images array.
event.images.push({
id: result.public_id,
url: result.secure_url
});
// Once image is pushed into the array, I'm removing it from my server's upload folder using unlinkSync function
fs.unlinkSync(`./uploads/${img.filename}`);
// When all the images are uploaded then I'm sending back the response
if (req.body.images.length === event.images.length) {
await event.save();
res.send({
event,
msg: 'Event created successfully'
});
}
});
});
}
} catch (e) {
res.status(400).send(e);
}
});
P.S. Go ahead and suggest some optimization solution for this code here

Upload and Retrieve PDF file to PostgreSQL using Node.js, Express and Knex

I am trying to upload and retrieve a PDF file to and from a PostgreSQL Db using Node.js, Express and Knex.
The DB column documentfile is file type Bytea.
The file seems to be uploading to the DB and is returned. The resulting PDF file (test3.pdf) does not want to open. I have been struggling with this for a long time now. Any help will be greatly appreciated!
Node.js code to upload the file :
app.get('/uploadfile', (req,res) =>{
fs.readFile('0203.pdf' function(err, imgData) {
console.log(imgData)
knex('documenttable').insert(
{documentname: '0203.pdf',
documentfile: [imgData]
})
.then( function (result) {
res.end(console.log("Document uploaded To DB"));
});
});
});
Node.js code to retrieve the file:
app.get('/dbfileback', function(req, res, next) {
knex('documenttable').where({
documentnumber: '1'
}).select('documentname', 'documentfile')
.then( function (result) {
fs.writeFile('test3.pdf', result[0].documentfile,'binary');
res.end(console.log("Done"));
});
});

Resources