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:
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()
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:
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()
Share Improve this question edited Jan 15, 2018 at 20:33 CommonSenseCode asked Jan 15, 2018 at 20:26 CommonSenseCodeCommonSenseCode 25.5k38 gold badges148 silver badges196 bronze badges 3-
Base64 strings for the
href
are perfectly valid - are you sure that your Base64 is indeed correct? Are you also sure that you have a PDF Viewer assigned to your 'Open With' for your browser? – Obsidian Age Commented Jan 15, 2018 at 20:29 - kinda looks like your data uri is missing a ",". Here is data uri format from mozilla documentation: data:[<mediatype>][;base64],<data> developer.mozilla/en-US/docs/Web/HTTP/Basics_of_HTTP/… Probably not your problem but I always like to start with the small stuff first. – victor Commented Jan 15, 2018 at 20:32
- @ObsidianAge pls see the update – CommonSenseCode Commented Jan 15, 2018 at 20:34
1 Answer
Reset to default 5If 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.