Skip to content

Commit

Permalink
Add support for complex path file downloading (#240)
Browse files Browse the repository at this point in the history
* Add complex path download

* Add support for suggested filename

* Update index.html

* Update routes.js

* Update routes.js
  • Loading branch information
jonathanKingston authored Oct 31, 2024
1 parent bc2ed62 commit 7301ffa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
7 changes: 7 additions & 0 deletions features/download/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<p>Download via iframe</p>
<ul>
<li><a href="#" class="init-iframe-download" data-type="json" >Init iframe JSON load</a>
<li><a href="#" class="init-iframe-download" data-type="json" data-suggestedFilename="./../path/path/testComplex.json.">Init iframe JSON load, complex suggested path</a>
<li><a href="#" class="init-iframe-download" data-type="pdf" >Init iframe PDF load</a>
</ul>
<div id="iframe-container"></div>
Expand All @@ -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);
});
});
Expand Down
7 changes: 4 additions & 3 deletions features/download/server/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 7301ffa

Please sign in to comment.