'Unable to download a sent file with fastify
Edit
No solutions worked for me, so I ended up doing the following:
// in handler
return reply.sendFile('my_script.sql', 'scripts');
// on the client
const { data } = await axios({
url: '/api/generate',
method: 'GET',
responseType: 'blob'
})
const url = window.URL.createObjectURL(new Blob([content]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'my_script.sql');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
This works like a charm
Original post:
I have a simple endpoint as follows:
fastify.get('/generate', async (request, reply) => {
console.log('endpoint hit'); // this line is printed
const filePath = path.join(__dirname, '..', '..', 'scripts', 'my_script.sql');
reply.sendFile(filePath, 'scripts');
})
This just sends the contents of the sql
file in text form like so:
I know that express has a res.download
method, but I couldn't find an analog with fastify.
What am I doing wrong here? How can I download this file?
Solution 1:[1]
You can use fastify-static
or by sending the right headers:
fastify.get('/', (request, reply) => {
const filePath = require('path').join(
__dirname,
'../../scripts/my_script.sql'
)
const stream = require('fs').createReadStream(filePath)
reply.header(
'Content-Disposition',
'attachment; filename=foo.sql'
reply.send(stream).type('application/sql').code(200)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Manuel Spigolon |