有什么方法可以在客户端创建一个文本文件,并提示用户下载它,而不与服务器进行任何交互? 我知道我不能直接写到他们的机器上(安全等),但是我可以创建并提示他们保存它吗?


当前回答

如果文件包含文本数据,我使用的一种技术是将文本放入textarea元素中,并让用户选择它(在textarea中单击,然后按ctrl-A),然后复制,然后粘贴到文本编辑器。

其他回答

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}



// Start file download.
download("hello.txt","This is the content of my file :)");

原文:https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

我将使用一个<a></a>标签,然后设置href='path'。然后,在<a>元素之间放置一个图像,这样我就可以直观地看到它。如果你想,你可以创建一个函数来改变href,这样它就不会是同一个链接,而是动态的。

如果你想用javascript访问<a>标签,也给它一个id。

从HTML版本开始:

<a href="mp3/tupac_shakur-how-do-you-want-it.mp3" download id="mp3Anchor">
     <img src="some image that you want" alt="some description" width="100px" height="100px" />
</a>

现在使用JavaScript:

*Create a small json file*;

const array = [
     "mp3/tupac_shakur-how-do-you-want-it.mp3",
     "mp3/spice_one-born-to-die.mp3",
     "mp3/captain_planet_theme_song.mp3",
     "mp3/tenchu-intro.mp3",
     "mp3/resident_evil_nemesis-intro-theme.mp3"
];

//load this function on window
window.addEventListener("load", downloadList);

//now create a function that will change the content of the href with every click
function downloadList() {
     var changeHref=document.getElementById("mp3Anchor");

     var j = -1;

     changeHref.addEventListener("click", ()=> {

           if(j < array.length-1) {
               j +=1;
               changeHref.href=""+array[j];
          }
           else {
               alert("No more content to download");
          }
}

上面所有的例子在chrome和IE中都运行良好,但在Firefox中却失败了。 请考虑将一个锚附加到主体上,并在点击后将其移除。

var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';

// Append anchor to body.
document.body.appendChild(a);
a.click();

// Remove anchor from body
document.body.removeChild(a);

来自github.com/kennethjiang/js-file-download的js-file-download包处理浏览器支持的边缘情况:

查看源代码以查看它如何使用本页中提到的技术。

安装

yarn add js-file-download
npm install --save js-file-download

使用

import fileDownload from 'js-file-download'

// fileDownload(data, filename, mime)
// mime is optional

fileDownload(data, 'filename.csv', 'text/csv')

如果你只是想把一个字符串转换成可以下载的,你可以使用jQuery尝试一下。

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