有没有一种方法可以为urlCreator.createObjectURL(blob)创建文件名?

5

我对Javascript不是很熟悉,有没有办法让我自己创建文件名?现在打开新标签页时文件名是Guid格式的。

if (urlCreator && headers['content-type'] != 'application/octet-stream') {
  // Fallback to $window.location method
  try {
    // Prepare a blob URL
    // Use application/octet-stream when using $window.location to force download
    var objectUrl = urlCreator.createObjectURL(blob);
    $window.open(objectUrl);
    success = true;
  } catch (ex) {
    //console.log("Download link method with $window.location failed with the following exception:");
    //console.log(ex);
  }
}

我猜你想留在用户这边。那么我知道的唯一选项,在支持的浏览器中,是使用锚元素(<a>)并将其download属性设置为所需的文件名,将其href设置为您获得的对象URL。但是那样你就无法使用window.open()。如果你想将文件保存在服务器上,你可以使用一个FormData对象来发送blob(而不是objectURL!),并将FormData.append()的第三个参数设置为你想要的文件名。 - Kaiido
谢谢回复 @Kaiido ,我会去研究它 :) - Gabriel Llorico
@Kaiido,上次我并不打算保存它,只是想检索一下。数据已经来自后端,我只是想在浏览器上查看它,并显示文件名 :) - Gabriel Llorico
4
你希望新窗口的标题为例如“yourFile.png (PNG 图像...)”?在 Firefox 中,你可以先使用 new File(blob, fileName) 将 Blob 转换为 File,但在 Chrome 中似乎无法实现。因此,最好的跨浏览器解决方案可能是 var win = window.open(URL.createObjectURL(blob)); win.onload = function(){ this.document.title = 'someFile.xxx';};。请注意,上述任何方法都无法在右键单击保存图像时设置文件名(如果我们谈论的是图像)。 - Kaiido
@Kaiido,谢谢,这正是我在寻找的 :) - Gabriel Llorico
1个回答

1

您可以使用FileSaver.js来实现这个:

var FileSaver = require('file-saver');
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接