RSSAmplifier

Pqina · Jul 12, 2022

How To Clone A File With JavaScript

0
Sign in to vote or save

Pqina · Pqina

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:

Rik Schennink

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

Or join my newsletter

Read the original on pqina.nl

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.