如何用JavaScript从文本创建文件 [英] How to create file in JavaScript from text

查看:71
本文介绍了如何用JavaScript从文本创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写JavaScript代码以启动浏览器中文件的下载.我能够以字符串的形式获取文件的字节,并希望将字符串传递给创建文件并从中启动下载的函数.

I am writing JavaScript code to initiate a download of a file in the browser. I am able to get the bytes of the file in a string and I want to pass the string to a function that creates a file and initiates a download from it.

我必须避免仅将文件存储在服务器上,以便有人通过html进行下载,例如:

I have to avoid just storing the file on the server for someone to download through html like:

<a href="./some-file.pdf">file</a>

到目前为止,这是我目前可以正常使用的代码,但是我需要修改文件的扩展名以更改它以匹配数据,这是我不知道的部分.

Here is the code I have so far which works just fine, but I need to modify the extension of the file to change it to match the data, which is the part I havn't figured out.

function download(data, filename = "aserc", type = ".txt") {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob)
    {
        window.navigator.msSaveOrOpenBlob(file, filename);
    } else  {
        var a = document.createElement("a"), url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

这将下载文件,但不是.txt文件.如何使用此代码更改文件的类型?

this will download a file but it will not be a .txt file. How do I change the type of the file using this code?

推荐答案

将文件扩展名添加到文件名中.像这样

Add the file extension to the name of the file. Like this

a.download = filename + ".txt";

查看Blob对象为type属性输入'plain/text'的文档以指定文本,您可能需要注意,将Blob声明更改为

Looking at the docs the Blob object takes in 'plain/text' for the type attribute to specify text this may be something you should keep an eye on, change Blob declaration to

var file = new Blob([data], {type: 'plain/text'});

这篇关于如何用JavaScript从文本创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆