Skip to content

Instantly share code, notes, and snippets.

@edysegura
Created July 10, 2024 17:43
Show Gist options
  • Save edysegura/fd629f301113a50f06c3688962894c4d to your computer and use it in GitHub Desktop.
Save edysegura/fd629f301113a50f06c3688962894c4d to your computer and use it in GitHub Desktop.
Force the download file
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