JS DOWNLOAD FILE
- User
User: JS DOWNLOAD FILE User: JS DOWNLOAD FILE Assistant:
- Assistant
To download a file using JavaScript, you can create a function that triggers the download of a file when called. Here's a simple example using the
Blobobject and theURL.createObjectURLmethod:function downloadFile(filename, content) { // Create a blob with the content const blob = new Blob([content], { type: 'text/plain' }); // Create a link element const link = document.createElement('a'); // Create a URL for the blob const url = URL.createObjectURL(blob); // Set link attributes link.href = url; link.download = filename; // Set the desired file name // Append to the body (necessary for Firefox) document.body.appendChild(link); // Programmatically click the link to trigger the download link.click(); // Remove the link from the document document.body.removeChild(link); // Release the object URL URL.revokeObjectURL(url); } // Usage downloadFile('example.txt', 'Hello, this is a sample text file!');Explanation:
-
Blob Creation: The
Blobconstructor creates a new blob object that contains the data you want to download. You can specify the MIME type (e.g.,'text/plain'). -
Creating a Link: An
<a>element is created and thehrefattribute is set to the object URL created from the blob. -
Triggering the Download: The
downloadattribute specifies the name of the file to be downloaded. The link is programmatically clicked to initiate the download. -
Cleanup: The link is removed from the document, and the object URL is revoked to free up memory.
You can call
downloadFilewith any filename and content to initiate a download. Adjust the MIME type based on the file type you are downloading (e.g.,application/pdffor PDFs). -