Download Any Files in HTML and JavaScript: Ultimate Tutorial

Robin
Updated on January 18, 2023

We have various methods to download any type of file using an HTML attribute and JavaScript. We can also fetch files from an external URL and download them by clicking a button.

The easiest solution is to use the download attribute on the <a> tag and set the path of a file in the href attribute. With this, the browser will download that file. We can also the <a> tag with all these attributes and click on it dynamically using JavaScript.

In this article, we will take a closer look at the various methods for downloading files from local paths and external URLs using JavaScript. These techniques work for any file type.

Download Files Using the HTML Attribute

You can use the download attribute on an HTML <a> tag to download a file. This attribute tells the browser to download the file instead of navigating to it.

          <!-- Use original file name for the downloaded file -->
<a href="./image.jpg" download>Download</a>

<!-- Use custom name for the downloaded file -->
<a href="./image.jpg" download="thumbnail.jpg">Download</a>
        

In this example, I have created an <a> tag with an image file path and the download attribute. When users click on the link, the browser will download and save that file on their device.

The downloaded file name will be the same as the original file name in the path. But there is a way to rename and give a custom name to that downloaded file.

Whatever you want to be the name, you can set it as the value of the download attribute. When users click the link to download, the browser will use it as the file name.

Also Read: Best Ways to Create Dynamic HTML Element & CSS in JavaScript

Programmatically Download Files With JavaScript

You can programmatically initiate the download using JavaScript if you want. For that, create an anchor element using createElement() method and set it's href and download attributes. Finally, use the click() method to trigger a click event on the anchor element.

          const download = (path, filename = 'default.jpg') => {
    const link = document.createElement('a')

    link.href = path
    link.download = filename
    link.style.display = 'none'

    document.body.appendChild(link)

    link.click()

    document.body.removeChild(link)
}

const btn = document.getElementById('btn')

btn.addEventListener('click', () => {
    download('./image.jpg', 'thumbnail.jpg')
})
        

In this example, I have a download() function that takes 2 arguments: "path" and "filename". The path argument is the location of the file that I want to download, and the filename argument sets the name of the downloaded file.

I am creating an <a> element using createElement() method. I am creating and setting the href and download attributes with the values of path and filename arguments respectively.

You have to append this link element to the document body using appendChild() method. To make it invisible, set the CSS display property to "none".

In order to download the file, trigger a "click" event on the link element using the click() method and then remove it from the document body calling the removeChild() method.

You can call this downlaod() function with the appropriate file path and a name, whenever users click a button. It will automatically download that file.

Also Read: Get File Extensions in JavaScript: 3 Easy Ways For You

How to Download Files From External URL With JavaScript

Sometimes we want to fetch a file from an external URL and download it. We can do it using fetch() and blob() methods in JavaScript. This technique is similar to the previous one except few things.

First, call the fetch() method with the external URL to get the response. Now use the blob() method in the response to make it Blob type. Finally, call the URL.createObjectURL() method and pass the Blob type to it. This will return a blob URL.

          const download = async (path, filename = 'default.jpg') => {
    const data = await fetch(path)
    const blob = await data.blob()
    const fileUrl = URL.createObjectURL(blob)

    const link = document.createElement('a')

    link.href = fileUrl
    link.download = filename
    link.style.display = 'none'

    document.body.appendChild(link)

    link.click()

    document.body.removeChild(link)
}

const btn = document.getElementById('btn')

btn.addEventListener('click', () => {
    download('https://example.com/image.jpg', 'thumbnail.jpg')
})

        

In this example, I am fetching the response from the path and then calling the blob() method on it. Finally, I am generating the URL with the createObjectURL() method.

Like the previous technique, you create an <a> element dynamically and use this URL as its href attribute. Now by triggering the "click" event on this link element, you can download the file.

Also Read: How to Convert Images to Data URLs Using JavaScript (Base64)

Conclusion

We have covered several techniques to download files using JavaScript and HTML attributes. You can use any one of these depending on your requirements.

If you want the easiest solution, just add the download attribute to your <a> tag. But if you need more control, you can dynamically create the <a> tag and set those attributes using JavaScript.

You can also add "Blob" to it if you want to fetch a file from an external source. There are many options and features available for us to download files using JavaScript.

Related Posts