Downloading Images

Using the `download` attribute on a link we can tell the browser to offer the linked resource as a download instead of navigate to it. With some JavaScript we can automate this and serve images as downloads when a user saves an image.

About the download attribute

The download attribute triggers the browser to download the resource a link points to.

<a href="my-image.jpg" download>Dowload this image</a>

Set a value to the download attribute to rename the file.

<a href="my-image.jpg" download="renamed-image.jpg">Dowload this image</a>

Downloading the output image

With Doka we get a File object as the result of an image edit action. We can use the createObjectURL to turn the File object into a URL for use in a link.

const url = URL.createObjectURL(outputImage);

By combining these two APIs in the Doka onconfirm callback we can automagically serve created images to the user.

Doka.create({

    onconfirm: (output) => {

        // we want the output file
        const file = output.file;

        // now we need a URL that points to the file object
        const url = URL.createObjectURL(output.file);

        // we create an invisible link
        const link = document.createElement('a');
        link.style.display = 'none';
        link.download = 'image.jpeg';
        link.href = url;

        // attach the link to the DOM to make this work in Firefox
        document.body.appendChild(link);

        // trigger the download
        link.click();

        // delay the remove and clean up action to make it work in Firefox
        setTimeout(() => {
            // remove our invisible link
            document.body.removeChild(link);

            // revoke the file URL to prevent memory leaks
            URL.revokeObjectURL(url);
        }, 0);

    }

    /* other properties */

})