Skip to content

Instantly share code, notes, and snippets.

@lzbgt
Created February 17, 2022 03:19

Revisions

  1. lzbgt created this gist Feb 17, 2022.
    7 changes: 7 additions & 0 deletions force-image-download-with-javascript.markdown
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    Force image download with JavaScript
    ------------------------------------
    Función para forzar la descarga de un archivo usando Javascript puro

    A [Pen](https://codepen.io/vladisalguero/pen/XWRozER) by [Vladimir Salguero](https://codepen.io/vladisalguero) on [CodePen](https://codepen.io).

    [License](https://codepen.io/license/pen/XWRozER).
    3 changes: 3 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Stack_Overflow_logo.svg/1280px-Stack_Overflow_logo.svg.png" download="Logo.png" >DOWNLOAD (only open)</a>
    <br><br>
    <button onclick="downloadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Stack_Overflow_logo.svg/1280px-Stack_Overflow_logo.svg.png', 'LogoStackOverflow.png')" >DOWNLOAD (forced)</button>
    16 changes: 16 additions & 0 deletions script.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    function downloadImage(url, name){
    fetch(url)
    .then(resp => resp.blob())
    .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    // the filename you want
    a.download = name;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    })
    .catch(() => alert('An error sorry'));
    }