0

Using a static HTML file can I embed base64 content in an object element like this:

<object data="data:application/pdf;base64,x0l3ACAAAA...LOTS MORE DATA" type="application/pdf" id="SOME_ID"></object>

And then somehow have a link to open that content (ideally in a new window or as a download), e.g.this, that does not appear to work:

<a href="SOME_ID" target="_blank">open file</a>

1 Answers1

1

Basic example using a 3x3 PNG (90 bytes) for a full test. Two links, included. One using standard HTML, the other uses Javascript. To be honest, not sure if it will work with very large PDF files.

function dlMe(e) {
    this.download = "3x3.png";
    this.href = document.getElementById("imgPng").getAttribute("data");
    return true;
}

window.onload = function() {
    var a = document.getElementById("dlJs");
    a.addEventListener("click",dlMe,false);
}
<object id="imgPng" type="image/png" data="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAAIUlEQVQI12P0iq78zwAFTAxIgOnv378Mf//+ZWBhYWEAAIIiCB0qP1ybAAAAAElFTkSuQmCC"></object>
<br />
<a href="#" id="dlJs">download with JS 3x3 image</a><br />
<a download="3x3.png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAAIUlEQVQI12P0iq78zwAFTAxIgOnv378Mf//+ZWBhYWEAAIIiCB0qP1ybAAAAAElFTkSuQmCC">download with HTML 3x3 image</a>
Tigger
  • 8,980
  • 5
  • 36
  • 40
  • This works a treat in chrome but fails in IE, don't suppose you have any idea about a workaround for that? (the message:"you'll need a new app to open this data") –  Jul 22 '18 at 11:01
  • 1
    @gordatron : I only have Linux (and FreeBSD) test with atm. I believe the problem may be the [`download` attribute before Edge 14](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a). Try removing `download` (for Edge / IE only). Works with Firefox and should work with Safari as well. – Tigger Jul 22 '18 at 11:07
  • yeah, i think it may be blocked form nearly all but images: https://stackoverflow.com/questions/17233034/data-uri-doesnt-work-with-ie –  Jul 22 '18 at 11:08
  • Thanks though as this is a very handy technique and support might increase. its a neat way of generating a rich document on the fly that has good potential for cross platform support etc. –  Jul 22 '18 at 11:09
  • You could do a hack for IE / Edge to force to a download URL instead with a `Content-Disposition: attachment; filename="3x3.png"` header and echo out the data until people stop using IE and Edge :] – Tigger Jul 22 '18 at 11:14