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


当前回答

这个解决方案直接从tiddlywiki的(tiddlywiki.com) github存储库中提取。我在几乎所有的浏览器中都使用过tiddlywiki,它就像一个魅力:

function(filename,text){
    // Set up the link
    var link = document.createElement("a");
    link.setAttribute("target","_blank");
    if(Blob !== undefined) {
        var blob = new Blob([text], {type: "text/plain"});
        link.setAttribute("href", URL.createObjectURL(blob));
    } else {
        link.setAttribute("href","data:text/plain," + encodeURIComponent(text));
    }
    link.setAttribute("download",filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

Github回购: 下载保护程序模块

其他回答

对我来说,这工作得很完美,下载了相同的文件名和扩展名

<a href={“数据:应用程序/ octestream;charset=utf-16le;base64]下载= =

'title'是带扩展名的文件名,例如sample.pdf, waterfall.jpg等。

'file64'是base64内容,例如,ww6idewndasifnsawrpbmdty2fszudyb3vwoiair3jvdxagqiisie1lzgljywxwaxnpdezsyxrgwu6idm1lcbezw50ywxqyvvyy2vudgfnztogmjusifbyb2nlzhvyzvblcmnlbnq6idcwlkcffsb7ikdyywjoir3jvdxagqinsawrpbmdty2fszudyb3vwijir3jvdxagqiisik1lzgljyw50ywxqyxlwuiojm1lcjzw50ywxqyxljuvgvycnkgtgliiwiugf0awvudexpc3qiolt7ilbhdglbnro

您可以使用数据uri。浏览器支持各不相同;看到维基百科。例子:

<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

八位流是强制下载提示符。否则,它可能会在浏览器中打开。

对于CSV,您可以使用:

<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>

试试jsFiddle演示。

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

上面所有的例子在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);

以下方法适用于IE10+、Edge、Opera、FF和Chrome浏览器:

const saveDownloadedData = (fileName, data) => {
    if(~navigator.userAgent.indexOf('MSIE') || ~navigator.appVersion.indexOf('Trident/')) { /* IE9-11 */
        const blob = new Blob([data], { type: 'text/csv;charset=utf-8;' });
        navigator.msSaveBlob(blob, fileName);
    } else {
        const link = document.createElement('a')
        link.setAttribute('target', '_blank');
        if(Blob !== undefined) {
            const blob = new Blob([data], { type: 'text/plain' });
            link.setAttribute('href', URL.createObjectURL(blob));
        } else {
            link.setAttribute('href', 'data:text/plain,' + encodeURIComponent(data));
        }

        ~window.navigator.userAgent.indexOf('Edge')
            && (fileName = fileName.replace(/[&\/\\#,+$~%.'':*?<>{}]/g, '_')); /* Edge */

        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

因此,只需调用函数:

saveDownloadedData('test.txt', 'Lorem ipsum');