如何下载使用JavaScript生成的文件,避免自动打开Chome? [英] How to download a file generated with JavaScript, avoiding automatic opening of Chome?

查看:80
本文介绍了如何下载使用JavaScript生成的文件,避免自动打开Chome?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发JavaScript小网络邮件.

I am developing a JavaScript little webmail.

我从服务器收到一个Base64编码的字符串,它表示一个文件(可以是任何类型).我解码字符串,将其映射到Uint8Array,并使用

I receive from the server a Base64-encoded string, that represents a file (it could be whatever type). I decode the string, a map it to a Uint8Array, and with it, I generate a Blob object with I create a data URI with

FileReader.readAsDataURL(blob)

直到这里非常简单,但是我在下载部分遇到了问题.

Until here is pretty straightforward, but I am having problem with the download part.

我将DataURI放入

I put the DataURI in

window.open(dataURI)

但是chrome打开了一个新窗口,并显示我的图像或文本.但是我需要避免这种行为,而是下载文件.

But chrome opens a new window and display my image, or my text. But I need to avoid this behaviour, and download the file instead.

我已经知道可以使用Content-Disposition "attachment"完成此操作,但是我不确定是否是我的情况,因为我是根据服务器中的字符串生成文件的.

I have red that this could be done with Content-Disposition "attachment" but I am not sure if it is my case, because I am generating the file from a string from the server.

有人可以帮助我理解吗?

Anyone who can help me understand?

推荐答案

您尝试使用"saveAs"吗?

Did you try to use "saveAs" ?

saveAs(blob, "hello.zip");

如果您需要广泛的浏览器支持,则可以尝试polifill. 更多信息

In the case you need wide browser support you could try polifill. More information

我很确定您可以设置Blob的类型

I am pretty sure you can set the type of the blob

var blob = new Blob(["Hello world!"], { type: "application/download" });

没有FileSaver.js:

without FileSaver.js:

var blob = new Blob(["Hi stack"], {type: 'application/download'});
var reader = new FileReader();
reader.onloadend = function(e) {
    window.open(reader.result);
}
reader.readAsDataURL(blob);

文档和浏览器支持信息(浏览器兼容性"标签):

Documentation and browser support information ("Browser compatibility" tab):

  • FileReader
  • Blob

这篇关于如何下载使用JavaScript生成的文件,避免自动打开Chome?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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