Created
July 10, 2024 17:43
-
-
Save edysegura/fd629f301113a50f06c3688962894c4d to your computer and use it in GitHub Desktop.
Force the download file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
context.server.get('/download-file/:name', async (req, res) => { | |
try { | |
const { url } = req.query | |
const { name } = req.params | |
if (!url || !name) { | |
return res.status(400).json({ error: 'Missing parameters' }) | |
} | |
const response = await fetch(url) | |
if (!response.ok) { | |
throw new Error(`Failed to fetch file: ${response.statusText}`) | |
} | |
res.setHeader('Content-Disposition', `attachment; filename="${name}"`) | |
res.setHeader('Content-Type', 'application/octet-stream') // Set as binary file to force download on mobile | |
response.body.pipe(res).on('error', (err) => { | |
res.status(500).json({ error: 'Error downloading file', details: err.message }) | |
}) | |
} catch (error) { | |
res.status(500).json({ error: 'Error downloading file', details: error.message }) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment