Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Create download link from FileReader or base64

I'm using the following code to onLoad of FileReader to create a tag and put inside the href the result from FileReader. Which is a base64 string.

   let reader = new FileReader()
    reader.readAsDataURL(myInputTypeFile.files[0])

    reader.onloadend = (e) => {
        let file
        for (let i = 0; i < attachInput.files.length; i++) {
            file = attachInput.files[i]

            if (file.type === 'application/pdf'){
                let anchor = document.createElement('a')
                anchor.setAttribute('class', 'q-attached-file')
                anchor.setAttribute('title', file.name)
                anchor.setAttribute('href', reader.result)
                anchor.innerText = file.name
                myElement.appendChild(anchor)
            }
        }
    }

This is the html produced: enter image description here

But when I click on the element I just see 'about:blank' loaded on browser.

UPDATE

this how the reader.result string is in console.log() enter image description here

like image 973
CommonSenseCode Avatar asked Mar 15 '26 17:03

CommonSenseCode


1 Answers

If your user is in a browser that supports the download attribute, you can add it to your anchor tag.

<a download href="...">

However not all browsers support the download attribute. Check the support tables.

There is a lib that does some tricky stuff to sidestep some of the differences between browsers. If you don't mind a few extra kb, try using DownloadJS.

like image 99
posit labs Avatar answered Mar 17 '26 08:03

posit labs