2

var a = 'Hello World From Javascript';在当前窗口的 javascript 变量中有一些文本数据(比如)。我想通过javascript执行以下操作-

1. open a new window and write the text data to the window.
2. set the content type to text/plain.
3. set the content-disposition to attachment, so that download prompt comes.
4. user downloads the text data as a text file and saves it to his local disk.

这一切都可以通过javascript实现吗?

我知道我们可以对服务器进行 ajax 调用或重定向,但在这种情况下,而不是遵循上述步骤。但在这种情况下,这些变通办法是不适应的。

4

5 回答 5

5

您可以使用 JS 和 HTML5 功能来做到这一点。请在下面找到示例代码。

        var fileParts = ['Hello World From Javascript'];

        // Create a blob object.
        var bb = new Blob(fileParts,{type : 'text/plain'});

        // Create a blob url for this. 
        var dnlnk = window.URL.createObjectURL(bb);

        var currentLnk = $('#blobFl').attr('href');

        // blobFl is the id of the anchor tag through which the download will be triggered.

        $('#blobFl').attr('href',dnlnk);
        $('#blobFl').attr('download','helloworld.txt');

        // For some reason trigger from jquery dint work for me.
        document.getElementById('blobFl').click();
于 2013-12-02T11:00:27.507 回答
3

在没有任何服务器请求的情况下触发文件下载

不幸的是,这不是您使用普通浏览器功能可以做到的。flash 或特定于浏览器的插件之类的东西可以满足您的需求,但 javascript 中的安全限制不会让您下载在浏览器中创建的任意数据。

此外,并非所有浏览器/版本组合都支持“数据”网址。我不确定您的用户是否受限于他们使用的浏览器,但这可能会限制您可以使用该解决方案做什么。

来源:在没有任何服务器请求的情况下触发文件下载

于 2012-11-25T08:39:16.703 回答
2

如果您已经在服务器上拥有该文件(我进行 ajax 调用以在服务器上生成并保存 PDF) - 您可以这样做

window.location.replace(fileUrl);
于 2013-07-09T09:26:49.833 回答
1

不,Content-Disposition 是一个响应头,它必须来自服务器。我认为你可以用 Flash 来做,但我不推荐它。

于 2012-11-25T03:59:37.583 回答
0

这是@Rajagopalan Srinivasan 答案的干净、纯 js 版本:

var fileParts = ["Hello World From Javascript"];
// The anchor tag to use.
const blobLink = document.getElementById("blobLink");
// Create a blob object.
var blob = new Blob(fileParts, { type: "text/plain" });

// Create a blob url for this.
var blobUrl = window.URL.createObjectURL(blob);

blobLink.setAttribute("href", blobUrl);
blobLink.setAttribute("download", "helloworld.txt");
blobLink.click();
<a id="blobLink">Download</a>
于 2021-03-25T16:06:14.903 回答