1

UPDATE:

Creating a Blob from a base64 string in JavaScript

I am trying to implement click a button and download file from its DataURL.

Currently, since the Chrome has restricted the old way such as building <a> link which throws error like:

Not allowed to navigate top frame to data URL: ....

The solution I found is open new window with iframe and set the DataURL as its src

let jpgWindow = window.open("", "_blank")
var html = "<html><body><iframe width='100%' height='100%' src='data:application/jpeg;base64, "+ theDataURL+"'></iframe></body></html>";
jpgWindow.document.write(html)

When I click the button, the download works, but the picture is downloaded with filename "download", there is no way I can specify what file name I want it default to.

Any thought?

Kuan
  • 11,149
  • 23
  • 93
  • 201

1 Answers1

2

Look into window.URL.createObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

const blob = new Blob(['array of data in your file'], {type : 'text/rtf'});
const anchor = document.createElement('a');

anchor.href = window.URL.createObjectURL(blob);
anchor.download = 'the-file-name.txt';
anchor.click();
Geuis
  • 41,122
  • 56
  • 157
  • 219