0

I am trying to create a button that triggers a download of a JSON file. (And please i don't want to use any libraries to achieve this). Thank you.

import Data from '../Data';

let data = Data;

<Button>Download</Button>
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
stanley pena
  • 61
  • 2
  • 8
  • Does this answer your question? [How to trigger a file download when clicking an HTML button or JavaScript](https://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript) – Emile Bergeron May 21 '20 at 18:14
  • Is the JSON static data? Why not just put the JSON file on the server and just provide a link for the user to click? – Emile Bergeron May 21 '20 at 18:16
  • @EmileBergeron how would i do that. Can you provide a sample code? – stanley pena May 21 '20 at 18:52
  • It really depends on your project setup. You should include an [mcve] and more information on the data, how the project is hosted, etc. Are you using Create-React-App? Next.js? Gatsby? React manually? – Emile Bergeron May 21 '20 at 19:03

3 Answers3

1

Triggering browser download from front-end is not reliable.

What you should do is, create an endpoint that when called, will provide the correct response headers, thus triggering the browser download.

Front-end code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser.

iamwebkalakaar
  • 358
  • 1
  • 9
1

Take a look at this solution: How to create a file in memory for user to download, but not through server? I have rewritten their code a bit, but basically for your case, you'd want...

    // Set globals
var mimetype = 'application/json';
var filename = 'yourfile.json';

    // Create Dummy A Element
var a = window.document.createElement('a');

    // createObjectURL for local data as a Blob type
a.href = window.URL.createObjectURL(new Blob([data], {
    encoding: "UTF-8",
    type: mimetype + ";charset=UTF-8",
}));
a.download = filename;

    // Download file and remove dummy element
document.body.appendChild(a);
a.click();
a.remove();
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
1

You would need to create a file using your data and then create a downloadable link and append it in whichever part of your application you would like to.

 const fileName = "file";
 const json = JSON.stringify(data);
 const blob = new Blob([json],{type:'application/json'});
 const href = await URL.createObjectURL(blob); // Create a downloadable link
 const link = document.createElement('a');       
 link.href = href;
 link.download = fileName + ".json";
 document.body.appendChild(link);   // This can any part of your website
 link.click();
 document.body.removeChild(link);
Muneeb
  • 1,469
  • 16
  • 24