简体   繁体   English

Javascript - 从FileReader或base64创建下载链接

[英]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. 我正在使用以下代码来onLoad FileReader来创建一个标记,并将来自FileReader的结果放在href中。 Which is a base64 string. 哪个是base64字符串。

   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: 这是html制作的: 在此输入图像描述

But when I click on the element I just see 'about:blank' loaded on browser. 但是当我点击元素时,我只是在浏览器上看到“about:blank”。

UPDATE UPDATE

this how the reader.result string is in console.log() 这个reader.result字符串如何在console.log()中 在此输入图像描述

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. 有一个lib做一些棘手的东西来回避浏览器之间的一些差异。 If you don't mind a few extra kb, try using DownloadJS . 如果您不介意几个额外的kb,请尝试使用DownloadJS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM