From 7301ffabd99259f999040ce374b13cee08adbc6a Mon Sep 17 00:00:00 2001 From: Jonathan Kingston Date: Thu, 31 Oct 2024 12:42:02 +0000 Subject: [PATCH] Add support for complex path file downloading (#240) * Add complex path download * Add support for suggested filename * Update index.html * Update routes.js * Update routes.js --- features/download/index.html | 7 +++++++ features/download/server/routes.js | 7 ++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/features/download/index.html b/features/download/index.html index 8aad172..0a31705 100644 --- a/features/download/index.html +++ b/features/download/index.html @@ -19,6 +19,7 @@

Download via iframe

@@ -34,6 +35,12 @@ const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = `./file/${link.dataset.type}`; + if (link.dataset.suggestedFilename) { + const params = new URLSearchParams({ + suggestedFilename: link.dataset.suggestedFilename + }); + iframe.src += '?' + params.toString() + } iframeContainer.appendChild(iframe); }); }); diff --git a/features/download/server/routes.js b/features/download/server/routes.js index 607be57..27a569c 100644 --- a/features/download/server/routes.js +++ b/features/download/server/routes.js @@ -5,21 +5,22 @@ function downloadPDF (res) { res.download('./features/download/download.pdf'); } -function downloadJSON (res) { +function downloadJSON (res, suggestedFilename) { const json = JSON.stringify({ example: 'test' }); const buf = Buffer.from(json); res.writeHead(200, { 'Content-Type': 'application/octet-stream', - 'Content-disposition': 'attachment; filename=data.json' + 'Content-disposition': `attachment; filename="${suggestedFilename}"` }); res.write(buf); res.end(); } router.get('/file/:type', (req, res) => { + const suggestedFilename = req.query.suggestedFilename || 'data.json'; switch (req.params.type) { case 'json': - downloadJSON(res); + downloadJSON(res, suggestedFilename); break; case 'pdf': downloadPDF(res);