方法一(支持Chrome和Firefox):

  1. function downloadTxt(filename, text) {
  2. const pom = document.createElement('a');
  3. pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  4. pom.setAttribute('download', filename);
  5. if (document.createEvent) {
  6. const event = document.createEvent('MouseEvents');
  7. event.initEvent('click', true, true);
  8. pom.dispatchEvent(event);
  9. } else {
  10. pom.click();
  11. }
  12. }

方法二(支持Chrome):

  1. function downloadTxt(filename, content, contentType) {
  2. if (!contentType) contentType = 'application/octet-stream';
  3. const a = document.createElement('a');
  4. const blob = new Blob([content], {'type': contentType});
  5. a.href = window.URL.createObjectURL(blob);
  6. a.download = filename;
  7. a.click();
  8. }

来源:https://www.jianshu.com/p/40cfe9a12f9e