How to create a file downloader via url using pure javascript

incoderweb

Ashutosh Tiwari

Posted on May 26, 2022

How to create a file downloader via url using pure javascript

Hello friends, today in this blog you will learn how to create a file downloader via URL using pure Javascript. In our previous blog, we saw how to create drag & drop or sortable lists using HTML, CSS, and Sortable JS. Earlier, I shared many projects related to javascript, you can check if you want, and don't forget to check HTML, CSS, and Javascript projects.

This tool (File Downloader via URL) can download any file like image, video, pdf, SVG, etc. Users have to paste a valid URL of the file and click the download button to download the file. Remember, the file should be publicly accessible to download.

At first, I got the user entered file URL, and using fetch() API, I fetched the file. Once I got a response, I return the response as a blob() and in another then method, I got an object that contains details of the file.

You may like these:

Then, using URL.createObjectURL() method, I created a URL of that file object. This URL is stored in the document window. At last, I created a <a> tag and stored the URL as the href value of this tag, and click it so the file download. Watch the above video for a detailed explanation of each JavaScript line.

Note: If you get a cors (cross-origin resource sharing) error in the console during file downloading, that means the browser blocked the request because the requested site doesn’t allow you to access that file.

This file downloader is made with pure JavaScript no server-side language is used to create it. If you liked it and want to create So you can check the source code or preview.

The Preview is available here.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Download Any File By URL Using Javascript - InCoder</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
</head>
<body>
    <div class="container">
        <div class="title">File Downloader via URL</div>
        <p>Paste url of any image, video or PDF to Download. This tool is made with pure Javascript</p>
        <form id="fileDownloader">
            <div class="formInput">
                <i class="fa-solid fa-link"></i>
                <input type="text" id="fileURL" placeholder="Paste the URL" oninvalid="this.setCustomValidity('Enter a valid URL')" required />
            </div>
            <button type="submit">Download</button>
        </form>
    </div>

    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS Code

/* ------------------------ Created By InCoder ------------------------ */

@import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #015d52;
}

.container {
  padding: 0.5rem;
  border-radius: 0.5rem;
  background-color: #fff;
  width: clamp(18rem, 45vw, 25rem);
}

.container .title {
  font-weight: 600;
  color: #202020;
  text-align: center;
  font-size: clamp(1rem, 4vw, 1.6rem);
}

.container p {
  font-size: 0.9rem;
}

.container button[type="submit"] {
  border: 0;
  width: 100%;
  opacity: 0.9;
  color: #fff;
  height: 2.5rem;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 0.8rem;
  border-radius: 0.3rem;
  background-color: #015d52;
  transition: opacity 0.2s ease-in-out;
}

.container button[type="submit"]:hover {
  opacity: 1;
}

.formInput input {
    border: 0;
    width: 100%;
    height: 100%;
    margin-left: .3rem;
}

.formInput input::placeholder {
    color: #4e4e4ed4;
}

.formInput {
  margin-top: .8rem;
  width: 100%;
  display: flex;
  height: 2.5rem;
  padding: .2rem;
  color: #4e4e4ed4;
  align-items: center;
  border-radius: .3rem;
  border: 2px solid #4e4e4ed4;
}

.formInput input:focus {
    outline: none;
}
Enter fullscreen mode Exit fullscreen mode

Javascript Code

let form = document.querySelector('#fileDownloader')
downloadBtn = form.querySelector('button')

form.addEventListener('submit', e => {
    e.preventDefault()
    let inputURL = e.target.querySelector('#fileURL').value.trim()
    downloadBtn.innerText = 'Downloading File Please Wait....'
    downloadBtn.setAttribute('disabled', 'disabled')
    getFile(inputURL)
})

const getFile = (url) => {
    fetch(url).then(response => response.blob()).then(file => {
        let tempLink = URL.createObjectURL(file)
        let anchorTag = document.createElement('a')
        anchorTag.href = tempLink
        anchorTag.download = url.replace(/^.*[\\\/]/, '')
        document.body.appendChild(anchorTag)
        anchorTag.click()
        downloadBtn.innerText = 'Download File'
        downloadBtn.removeAttribute('disabled', 'disabled')
        URL.revokeObjectURL(tempLink);
        anchorTag.remove();
    }).catch(() => {
        alert("Unable to download file!");
        downloadBtn.innerText = "Download File";
        downloadBtn.removeAttribute('disabled', 'disabled')
    })
} 
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
incoderweb
Ashutosh Tiwari

Posted on May 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related