How To Clone A File With JavaScript

A short code example showing how to create a clone (or copy) from a File object received from a file input element.

We’ll use a file input element as a source for the file.

<input type="file" />

<script>
    document.querySelector('input').addEventListener('change', (e) => {
        // we'll get the first file in the file input
        const original = e.target.files[0];

        // no file received, exit
        if (!original) return;

        // create our clone
        const clone = new File([original], original.name, {
            type: original.type,
            lastModified: original.lastModified,
        });

        // log the original, the clone, and a comparison to the console
        console.log(original, clone, original === clone);
    });
</script>

Open your developer console and test it out below:

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

More articles More articles