Filename of downloaded file in data:Application/octet-stream;

穿精又带淫゛_ 提交于 2019-11-30 06:10:10
Ashraf Bashir

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...

For those that are using other libraries like angularjs or backbone, you can try something like this.

$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+$scope.data);

I had the same issue and finally I solved in all browsers serving the CSV file in the server-side:

const result = json2csv({ data });

res.writeHead(200
        'Content-Type': 'application/octet-stream',
        'Content-Disposition': 'attachment;filename=issues.csv',
        'Content-Length': result.length
});

res.end(result);
Synedh

For anybody looking for a client-side solution using Javascript only, here is mine, working on any browser except IE 10 and lower (and Edge...why?!):

var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(csv);
var link = document.createElement('a');
link.setAttribute("download", "extract.csv");
link.setAttribute("href", uri);
document.body.appendChild(link);
link.click();
body.removeChild(body.lastChild);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!