Create and download a file in javascript
By Anatoly Mironov
Phew, I spent a lot of time to get this to work:
- Create a text based file in javascript - a simple csv or txt
- Download a file in Chrome and Internet Explorer
- Make Excel understand Unicode characters (å ä ö and many more) in csv directly.
I found many solutions on the Internet that I used to find out a solution that works for me A deep diving jsfiddle about unicode encodings, bom, line endings: http://jsfiddle.net/kimiliini/HM4rW (unfortunately, does not work in IE). There I learned one important thing: we need a BOM in order to make Excel understand that it is not just ASCII. The BOM (byte order mark) for utf-8 is %ef%bb%bf for utf-8. Without this bom you’ll see the right characters in a text editor (except Notepad of course), but if you open the csv file directly in Excel, you’ll see wrong letters. Other good resources are FileSaver.js: https://github.com/eligrey/FileSaver.js and download.js: http://danml.com/download.html and a discussion on that github repository issue: https://github.com/mholt/PapaParse/issues/175 This is my solution that is tested in Chrome and IE10: [code language=“javascript”] function downloadContent(options) { if (!options || !options.content) { throw ‘You have at least to provide content to download’; } options.filename = options.filename || ’tolle.txt’; options.type = options.type || ’text/plain;charset=utf-8’; options.bom = options.bom || decodeURIComponent(’%ef%bb%bf’); if (window.navigator.msSaveBlob) { var blob = new Blob([options.bom + options.content], {type: options.type }); window.navigator.msSaveBlob(blob, options.filename); } else { var link = document.createElement(‘a’); var content = options.bom + options.content; var uriScheme = [‘data:’, options.type, ‘,’].join(’’); link.href = uriScheme + content; link.download = options.filename; //FF requires the link in actual DOM document.body.appendChild(link); link.click(); document.body.removeChild(link); } } //test var separator = ‘;’; downloadContent({ type: ’text/csv;charset=utf-8’, filename: ’tolle.csv’, content: [‘ASCII’, separator, ‘Åbäcka sig’, separator, ’to się podoba: żźćąęłć’, separator, ‘Яшлӑхӑма туйаймарӑм’].join(’’) }); [/code]
Safari
So it works on the latest Chrome (tested with 50 on Windows, Mac and Linux), Firefox (tested with 46 on Windows), Internet Explorer (tested with 11 on Windows 7). Unfortunately in Safari on a Mac, the link is opened directly in the web browser. You have to press Cmd - S to trigger Save As manually.
Part of SharePoint Utilities
I submitted this code to sputils (SharePoint Utilities) on github.