Search code examples
javascripthtmldata-uri

Making a downloadable file with the dataURL


I am trying to make a downloadable file from only a dataURL and I am not sure why it is not working. I am reading the dataURL from a file and inserting its dataURL into an with the download attribute. but when i generate de click the page goes blank and says it can´t find the page. Here is how I am trying to do it.

reader.readAsDataURL(file);
reader.onload = function (evt) {
    var element = document.createElement('a');
    element.setAttribute('href', evt.target.result);
    var name=filename.split(".");
    element.setAttribute('download', 'filename');

    element.style.display = 'inline-block';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
 }

From the code above I obtain this

enter image description here

How can I properly make a download action for the dataURL?


Solution

  • Your approach is wrong.

    The readAsDataURL method is used to read the contents of the specified Blob or File. The result will be base64 encoded string.

    The readAsDataUrl method can be used to make a image preview.

    To download the file you can go by this approach

    <!DOCTYPE html>
    <html>
      <head> </head>
      <body>
         <form>
            <label for="file">ChooseFile</label>
            <input type="file" id="myFile" accept="image/*">
        </form>
    
        <script>
            document.getElementById("myFile").addEventListener("change", downloadFile);
    
            function downloadFile() {            
                let file = this.files[0];
                let url = URL.createObjectURL(file);
    
                let link = document.createElement('a');
                link.href = url;
                link.download = file.name;
                link.click();
                link = null;
    
                URL.revokeObjectURL(url);
            }
        </script>
      </body>
    </html>
    

    Useful resources