試試這個代碼:
$('#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>
這就是不同的瀏覽器如何處理它。看看這個:http://stackoverflow.com/questions/14388994/forcing-a-download-using-filesmatch-in-htaccess-at-www-root – Alex
@Alex請給出答案。無法清楚地瞭解您的鏈接。 –
你能用這個php嗎? – anil