Download the generated image

Using the web URL.createObjectURL API we can turn a file object into a URL and offer it as a download to the client.

To prevent memory leaks we have to revoke the URL with the URL.revokeObjectURL function when we no longer need the image.

Learn more about downloading files in the browser

import { openDefaultEditor } from './doka.js';

// Open the default image editor in a modal
const editor = openDefaultEditor({
    src: './my-image.jpeg',
});

// We'll use this helper function to download files
const downloadFile = (file) => {
    // Create a hidden link and set the URL using `createObjectURL`
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = URL.createObjectURL(file);
    link.download = file.name;

    // We need to add the link to the DOM for "click()" to work
    document.body.appendChild(link);
    link.click();

    // To make this work on Firefox we need to wait a short moment before clean up
    setTimeout(() => {
        URL.revokeObjectURL(link.href);
        link.parentNode.removeChild(link);
    }, 0);
};

// Wait for image to finish processing and capture output file
editor.on('process', (res) => downloadFile(res.dest));