没有链接的 JavaScript blob 文件名 [英] JavaScript blob filename without link

查看:34
本文介绍了没有链接的 JavaScript blob 文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过 window.location 强制下载一个 blob 文件时,如何在 JavaScript 中设置它的名称?

How do you set the name of a blob file in JavaScript when force downloading it through window.location?

function newFile(data) {
    var json = JSON.stringify(data);
    var blob = new Blob([json], {type: "octet/stream"});
    var url  = window.URL.createObjectURL(blob);
    window.location.assign(url);
}

运行上面的代码会立即下载一个文件,而无需刷新如下所示的页面:

Running the above code downloads a file instantly without a page refresh that looks like:

bfefe410-8d9c-4883-86c5-d76c50a24a1d

我想将文件名设置为 my-download.json.

I want to set the filename as my-download.json instead.

推荐答案

我所知道的唯一方法是 FileSaver.js:

The only way I'm aware of is the trick used by FileSaver.js:

  1. 创建一个隐藏的 标签.
  2. 将其 href 属性设置为 blob 的 URL.
  3. 设置其download 属性到文件名.
  4. 点击 标签.
  1. Create a hidden <a> tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the filename.
  4. Click on the <a> tag.

这是一个简化的示例(jsfiddle):

Here is a simplified example (jsfiddle):

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
        var json = JSON.stringify(data),
            blob = new Blob([json], {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);

我写这个例子只是为了说明这个想法,在生产代码中使用 FileSaver.js.

I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.

注意事项

  • 较旧的浏览器不支持下载"属性,因为它是 HTML5 的一部分.
  • 浏览器认为某些文件格式不安全,下载失败.保存带有 txt 扩展名的 JSON 文件对我有用.

这篇关于没有链接的 JavaScript blob 文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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