I am trying to download a file using data uri in following manner:
<input type="button" onclick="window.location.href='data:Application/octet-stream;content-disposition:attachment;filename=file.txt,${details}'" value="Download"/>
The problem is that the downloaded file is always named 'Unknown', whatever I try to use as filename. Is this the correct way to give the file a name ? or something else needs to be done ?
A MIME attachment with the content type application/octet-stream is a binary file. Typically, it is an application or a document that is opened in an application such as a spreadsheet or word processor.
The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data. The set of currently defined parameters is: (1) TYPE -- the general type or category of binary data. This is intended as information for the human recipient rather than for any automatic processing.
APPLICATION/OCTET-STREAM stands for binary data. It may be more precise by specifing the actual filetype. For images it coud be image/png . If the browser knows the exact filetype it may show the file directly.
Here's the solution, you just have to add a download
attribute to anchor tag a
with desired name
<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>
Another solution is to use JQuery/Javascript
Anchor's Download Property
On Safari, you might want to use this, and instruct the user to ⌘-S the file:
window.open('data:text/csv;base64,' + encodeURI($window.btoa(content)));
Otherwise, this uses Filesaver.js, but works ok:
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); } }
Note: There is some AngularJS in the code above, but it should be easy to factor out...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With