CommonSenseCode
CommonSenseCode

Reputation: 25369

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

Upvotes: 3

Views: 6780

Answers (1)

posit labs
posit labs

Reputation: 9431

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.

Upvotes: 5

Related Questions