我试图以下列方式使用数据uri下载文件:
<input type="button"
onclick="window.location.href='data:Application/octet-stream;content-disposition:attachment;filename=file.txt,${details}'"
value="Download"/>
Run Code Online (Sandbox Code Playgroud)
问题是下载的文件总是被命名为"未知",无论我尝试用作文件名.这是给文件命名的正确方法吗?或者其他什么需要做?
Ash*_*hir 36
这是解决方案,您只需要为具有所需名称的download锚标记添加属性
a
<a href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333"
download="somedata.csv">Example</a>
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是使用JQuery/Javascript
在 Safari 上,您可能想要使用它,并指示用户 ?-S 文件:
window.open('data:text/csv;base64,' + encodeURI($window.btoa(content)));
Run Code Online (Sandbox Code Playgroud)
否则,这使用Filesaver.js,但工作正常:
var downloadFile = function downloadFile(content, filename) {
var supportsDownloadAttribute = 'download' in document.createElement('a');
if(supportsDownloadAttribute) {
var link = angular.element('<a/>');
link.attr({
href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(content)),
target: '_blank',
download: filename
})[0].click();
$timeout(function() {
link.remove();
}, 50);
} else if(typeof safari !== 'undefined') {
window.open('data:attachment/csv;charset=utf-8,' + encodeURI(content));
} else {
var blob = new Blob([content], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:上面的代码中有一些 AngularJS,但应该很容易分解...