在我的网站中,我正在尝试使用以下代码下载文件。它在chrome中正常工作并下载文件。但是在firefox中它的打开文件在其他标签中播放。请建议任何其他方法下载MP3
仅供参考:文件正在从其他网站下载,请给我一个与mp3文件下载相关的答案,而不是任何文本下载。可能与交叉原始下载有关。
代码:
var anchor = document.createElement('a');
anchor.href= 'http://www.example.com/Albums/NameOfalbum/songname.mp3'; //Cross Origin
anchor.download= 'FileName.mp3';
anchor.target='_blank';
anchor.id='download';
if(navigator.userAgent.indexOf("Chrome") != -1 )
anchor.click();
else if(navigator.userAgent.indexOf("Firefox") != -1 )
$("#download")[0].click();
答案 0 :(得分:0)
您可以使用隐藏的iframe。
if (x mod 3 = 0 || x mod 2 = 0) then
这是HTML代码:
function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
};
或者,如果您想使用像PHP这样的服务器端语言,请点击此链接。
http://www.web-development-blog.com/archives/php-download-file-script/
答案 1 :(得分:0)
试试这段代码:
$('#downloadButton').click(function () {
// some data to export
var data = [{
"title": "Book title 1",
"author": "Name1 Surname1"
}, {
"title": "Book title 2",
"author": "Name2 Surname2"
}, {
"title": "Book title 3",
"author": "Name3 Surname3"
}, {
"title": "Book title 4",
"author": "Name4 Surname4"
}];
// prepare CSV data
var csvData = new Array();
csvData.push('"Book title","Author"');
data.forEach(function (item, index, array) {
csvData.push('"' + item.title + '","' + item.author + '"');
});
// download stuff
var fileName = "data.csv";
var buffer = csvData.join("\n");
var blob = new Blob([buffer], {
"type": "text/csv;charset=utf8;"
});
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
link.setAttribute("href", window.URL.createObjectURL(blob));
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
alert('CSV export only works in Chrome, Firefox, and Opera.');
}
});
HTML:
<div class="toggle-button" id="downloadButton"><span>Export to CSV</span>
</div>
Download attribute not working in Firefox
PS: HTML anchor tag download attribute not working in Firefox for jpg and png files
var links = document.querySelectorAll("a"), i = 0, lnk;
while(lnk = links[i++]) {
if (lnk.dataset.link.length) lnk.onclick = toBlob;
}
function toBlob(e) {
e.preventDefault();
var lnk = this, xhr = new XMLHttpRequest();
xhr.open("GET", lnk.dataset.link);
xhr.responseType = "blob";
xhr.overrideMimeType("octet/stream");
xhr.onload = function() {
if (xhr.status === 200) {
window.location = (URL || webkitURL).createObjectURL(xhr.response);
}
};
xhr.send();
}
HTML:
<a href="#" data-link="image.jpg">Click to download</a>