Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)

JS DOWNLOAD FILE

  1. User

    User: JS DOWNLOAD FILE User: JS DOWNLOAD FILE Assistant:

  2. 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 Blob object and the URL.createObjectURL method:

    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:

    1. Blob Creation: The Blob constructor creates a new blob object that contains the data you want to download. You can specify the MIME type (e.g., 'text/plain').

    2. Creating a Link: An <a> element is created and the href attribute is set to the object URL created from the blob.

    3. Triggering the Download: The download attribute specifies the name of the file to be downloaded. The link is programmatically clicked to initiate the download.

    4. Cleanup: The link is removed from the document, and the object URL is revoked to free up memory.

    You can call downloadFile with any filename and content to initiate a download. Adjust the MIME type based on the file type you are downloading (e.g., application/pdf for PDFs).