Javascript 上的文件下载在 Firefox 上不起作用

Posted

技术标签:

【中文标题】Javascript 上的文件下载在 Firefox 上不起作用【英文标题】:File Download on Javascript does not work on firefox 【发布时间】:2014-11-24 21:00:21 【问题描述】:

已经编写了这段代码,它在谷歌浏览器上运行完美,但在 Firefox 上运行不正常,你有什么线索吗?

预期的行为是您将 xml 文本和名称作为参数传递,它会下载一个带有该 xml 文本和您发送的名称的 xml 文件,正如我所说,对于 chrome 可以,但对于 firefox,它不会下载吧。

/** * 从查询结果的选定行创建和下载文件 * @param xml文本 * @param 文件名 */

函数 createAndDownloadFile(xmltext, 文件名)

var pom = document.createElement('a');
//creates a blob variable with the xml text
var bb = new Blob([xmltext], type: 'text/xml');

//sets the atribute href
pom.setAttribute('href', window.URL.createObjectURL(bb));
pom.setAttribute('download', filename);

//creates the download url
pom.dataset.downloadurl = ['text/xml', pom.download, pom.href].join(':');
pom.draggable = true; 
pom.classList.add('dragout');

//apply the click on to download the file
pom.click();

【问题讨论】:

【参考方案1】:

我有一个非常相似的问题,刚刚在 *** 上为我回答了这个问题:Download attribute not working in Firefox

尝试在点击事件之前将元素添加到 DOM:

//apply the click on to download the file
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);

【讨论】:

您好 MattSidor 非常适合我,非常感谢您的帮助。 很高兴听到这个消息。您能帮我一个忙,然后单击我的答案左侧的绿色复选标记,告诉其他人它回答了您的问题吗?非常感谢!

以上是关于Javascript 上的文件下载在 Firefox 上不起作用的主要内容,如果未能解决你的问题,请参考以下文章