How to download a file generated with JavaScript, avoiding automatic opening of Chome?

六眼飞鱼酱① 提交于 2019-12-08 02:07:48

问题


I am developing a JavaScript little webmail.

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.

I put the DataURI in

window.open(dataURI)

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.

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?


回答1:


Did you try to use "saveAs" ?

saveAs(blob, "hello.zip");

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

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

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

Edit:

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

Edit:

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

  • FileReader
  • Blob


来源:https://stackoverflow.com/questions/32562347/how-to-download-a-file-generated-with-javascript-avoiding-automatic-opening-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!