Download .txt file stored on server using Hapi js - node.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

Related

Download CSV at client end by REST API In Nest JS

I have a array of object data from which I am creating a csv. After Generation Of CSV it should get download at client side.At client side I am using Angular and at backend it is Nest Js.
I don't want to send link to client end to download csv . it should be done by REST API
you can use this sendFile function from the Response, Exemple:
async DownloadFile(#Res() res) {
try {
....
return res.sendFile(pathfile, { root: './files' });
}catch(e) {
...
}
}
And for the frontEnd (as is in your case is Angular) you can use file-saver to download the file, to give you a hand, here is an example:
let FileSaver = require('file-saver'); // path to file-saver
....
downloadFile(data: any) { // data : WebService response
const blob = new Blob([data], { type: 'text/csv' });
FileSaver.saveAs(blob, 'filename.csv');
}

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

download files from a dropbox folder

I'm using node.js and the dropbox package to download files from a folder. I'm able to authenticate and list the files, but not downloading them. I'd like to be able to download none shared files as well.
client.filesListFolder({ path: directory })
.then(function (response) {
response.entries.forEach(function (entry) {
if (entry[".tag"] === "file") {
client.filesDownload({ url: entry.path_display})
.then(function (data) {
// ...
})
.catch(function (err) {
throw err;
});
}
});
})
.catch(function (err) {
me.ThrowError(null, err.status, err.error);
});
Read this link:
https://blogs.dropbox.com/developers/2015/04/a-preview-of-the-new-dropbox-api-v2/
filesDownload({ url: entry.path_display}) passed a wrong arg.
I think it should be {path: entry.path_display}
I actually just tried it, but I only get the file object, I don't know how to get the file data be downloaded. It is may be because I am using Electron.js
As discussed in their github issue:
https://github.com/dropbox/dropbox-sdk-js/issues/88
Therefore, you could try to use function filesGetTemporaryLink({ path: entry.path_display})to a temp link and then use sharingGetSharedLinkFile({ url: res.link })

stripe fileUploader in meteor js gives error for the fakepath

I am trying to upload a verification document on stripe upload with below meteor method :
I am passing an object that contains the users identification document to to uploaded on the strip server for verification.
when I write the below method to upload the image file which is a png on the stripe server it gives me an error saying
"Error: ENOENT, no such file or directory 'C:\fakepath\success.png']"
Meteor.methods({
fileUploader("C:\\fakepath\\success.png"){ // path only for reference purpose
let fp = fs.readFileSync("C:\\fakepath\\success.
let StripefileUpload = new Future();
let file;
Stripe.fileUploads.create({
purpose: 'identity_document',
file: {
data: fp,
name: 'success.png',
type: 'application/octet-stream'
}
}, function(err, fileUpload) {
if (err) {
console.log(err);
StripefileUpload.return(err);
} else {
file = fileUpload.id;
console.log(file);
StripefileUpload.return(file);
}
});
return StripefileUpload.wait();
}
})
Have you tried putting the file somewhere relative to the project? (ie. put it in the working directory?)

Resources