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


当前回答

如前所述,filesaver是在客户端处理文件的一个很棒的包。但是,它不能很好地处理大文件。streamsave .js是一个可以处理大文件的替代解决方案(在FileServer.js中指向):

const fileStream = streamSaver.createWriteStream('filename.txt', size);
const writer = fileStream.getWriter();
for(var i = 0; i < 100; i++){
    var uint8array = new TextEncoder("utf-8").encode("Plain Text");
    writer.write(uint8array);
}
writer.close()

其他回答

HTML5浏览器的简单解决方案…

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); } form * { display: block; margin: 10px; } <form onsubmit="download(this['name'].value, this['text'].value)"> <input type="text" name="name" value="test.txt"> <textarea name="text"></textarea> <input type="submit" value="Download"> </form>

使用

download('test.txt', 'Hello world!');

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

来自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')

我很高兴使用FileSaver.js。它的兼容性非常好(IE10+和其他版本),而且使用起来非常简单:

var blob = new Blob(["some text"], {
    type: "text/plain;charset=utf-8;",
});
saveAs(blob, "thing.txt");