JavaScript blob文件名无链接 [英] JavaScript blob filename without link

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

问题描述

如果你通过window.location强制下载它,你如何设置一个blob文件的名称?

  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);
}

运行上面的代码立即下载一个文件,而不需要像bfefe410那样的页面刷新-8d9c-4883-86c5-d76c50a24a1d。我想将文件名设置为my-download.json。

解决方案

我知道的唯一方法是把戏由 FileSaver.js 使用:


  1. 创建一个隐藏的< a> 标签。

  2. 设置 href 属性到blob的URL。

  3. 设置其 下载 属性到文件名。

  4. 点击< a> 标签。

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

  var saveData =(function(){
var a = document.createElement(a);
document.body.appendChild (a);
a.style =display:none;
返回函数(data,fileName){
var json = JSON.stringify(data),
blob =新的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。 p>

备注




  • 旧版浏览器不支持下载属性,因为它是HTML5的一部分。

  • 某些文件格式被浏览器视为不安全,下载失败。使用txt扩展名保存JSON文件对我有用。


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. I want to set the filename as my-download.json instead.

解决方案

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

  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.

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);

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

Notes

  • Older browsers don't support the "download" attribute, since it's part of HTML5.
  • Some file formats are considered insecure by the browser and the download fails. Saving JSON files with txt extension works for me.

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

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