We have a ReactJS web app which uses an iframe to embed PDF in the page. We download the PDF as a byte array, then store it as a blob URL. It works in all browsers except Safari. We use createURLObject which creates a local url like blob:http://domain/guid.
If I grab this URL and open it in another tab, it shows the PDF. Not in Safari. It redirects to favorites with a random Guid and fails.
It seems Safari has issues with blobs or PDFs.
I tried changing it from a blob url to a data URL using a file reader. Only difference is that Safari can render the data url in another tab but not in an iframe.
The iframe loads but the body is empty with the message 'no supported plugin found'. Im running out of idea and think Safari just sucks
downloadPDf(customerId) {
this.api.downloadContract(customerId)
.then(response => {
const pdfData = new Blob(response.data.conent, 'application/pdf');
reader.onload = () => {
this.setState({dataUrl : reader.result });
}
reader.readAsDataURL(pdf);
}
Then in the JSX:
<iframe src={this.state.dataUrl} .... />
Once the file reader is loaded, the result will have a data URL containing the RAW data for the PDF.
It looks like something like this: data:application/pdf:byte64:<FILE_CONTENT>
This wont render in the iframe, but pasting it into a new tab will actually render the PDF correctly.
Our original code relied on Blob URLS which is like this:
downloadPDf(customerId) {
this.api.downloadContract(customerId)
.then(response => {
const pdfData = new Blob(response.data.conent, 'application/pdf');
const dataUrl = window.URL.CreateURLObject(blob);
}
This will create a local blob url which looks like: blob:http://localhost/
Pasting this into another tab does not work in Safari. It works in Edge, Chrome, and FireFox.
The downside of using the data URL is the file reader and a callback.
Following is my code which sets src attribute of an iframe to the blob url that I have created:-
function downloadFromIframeUsingBody(filebody: any) {
const iframe = document.createElement('iframe');
iframe.setAttribute('style', 'display: none;');
const newurl = window.URL.createObjectURL(new Blob([filebody.data],{type: 'application/pdf'}));
iframe.setAttribute('src', newurl);
const register = () => {
if (iframe.contentWindow) {
setTimeout(function() {
// Clean after 1 minute, by then it should already have started downloading
iframe.parentNode!.removeChild(iframe);
}, 60000);
} else {
setTimeout(register, 100);
}
};
register();
document.body.appendChild(iframe);
}
What I would like is for this iframe to download the blob containing pdf to be downloaded automatically. Currently nothing happens when this gets executed.
If you mean "download" as "save on disk" then just use an HTMLAnchorElement and its download attribute.
Or even handle all the edge cases (old IE and Safari quirks) with the ligthweight FileSaver script.
var blob = new Blob(["I'm just a text file..."], {type: 'plain/text'});
saveAs(blob, 'myFile.txt');
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.js"></script>
Note that this is true for any cases. iframe hack is just a bad hack that should only be used when it's been determined that no other better ways will work.
Now to explain why it won't work, well, it's because browsers actually are able to display pdf files, and will thus [try to] do it instead of forcing a download.
<iframe src="https://cdn.jsdelivr.net/gh/mozilla/pdf.js/test/pdfs/S2.pdf"></iframe>
(Note that current Chrome seems to have a bug that will make the pdf-reader to fail when in nested iframes, so here is a link to a plunker, where you can see it live in this browser by clicking the expand button on the right panel.
This question already has answers here:
How to create a file in memory for user to download, but not through server?
(22 answers)
Closed 2 years ago.
I have data that I want to write to a file, and open a file dialog for the user to choose where to save the file. It would be great if it worked in all browsers, but it has to work in Chrome. I want to do this all client-side.
Basically I want to know what to put in this function:
saveFile: function(data)
{
}
Where the function takes in data, has the user select a location to save the file, and creates a file in that location with that data.
Using HTML is fine too, if that helps.
A very minor improvement of the code by Awesomeness01 (no need for anchor tag) with addition as suggested by trueimage (support for IE):
// Function to download data to a file
function download(data, filename, type) {
var file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
Tested to be working properly in Chrome, FireFox and IE10.
In Safari, the data gets opened in a new tab and one would have to manually save this file.
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
click here to download your file
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>
And you would then download the file by putting the download attribute on the anchor tag.
The reason I like this better than creating a data url is that you don't have to make a big long url, you can just generate a temporary url.
This project on github looks promising:
https://github.com/eligrey/FileSaver.js
FileSaver.js implements the W3C saveAs() FileSaver interface in
browsers that do not natively support it.
Also have a look at the demo here:
http://eligrey.com/demos/FileSaver.js/
Choosing the location to save the file before creating it is not possible. But it is possible, at least in Chrome, to generate files using just JavaScript. Here is an old example of mine of creating a CSV file. The user will be prompted to download it. This, unfortunately, does not work well in other browsers, especially IE.
<!DOCTYPE html>
<html>
<head>
<title>JS CSV</title>
</head>
<body>
<button id="b">export to CSV</button>
<script type="text/javascript">
function exportToCsv() {
var myCsv = "Col1,Col2,Col3\nval1,val2,val3";
window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
}
var button = document.getElementById('b');
button.addEventListener('click', exportToCsv);
</script>
</body>
</html>
For latest browser, like Chrome, you can use the File API as in this tutorial:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);
function SaveBlobAs(blob, file_name) {
if (typeof navigator.msSaveBlob == "function")
return navigator.msSaveBlob(blob, file_name);
var saver = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
var blobURL = saver.href = URL.createObjectURL(blob),
body = document.body;
saver.download = file_name;
body.appendChild(saver);
saver.dispatchEvent(new MouseEvent("click"));
body.removeChild(saver);
URL.revokeObjectURL(blobURL);
}
Tried this in the console, and it works.
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));
You cannot do this purely in Javascript. Javascript running on browsers does not have enough permission yet (there have been proposals) due to security reasons.
Instead, I would recommend using Downloadify:
A tiny javascript + Flash library that enables the creation and download of text files without server interaction.
You can see a simple demo here where you supply the content and can test out saving/cancelling/error handling functionality.
For Chrome and Firefox, I have been using a purely JavaScript method.
(My application cannot make use of a package such as Blob.js because it is served from a special engine: a DSP with a WWWeb server crammed in and little room for anything at all.)
function FileSave(sourceText, fileIdentity) {
var workElement = document.createElement("a");
if ('download' in workElement) {
workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText);
workElement.setAttribute("download", fileIdentity);
document.body.appendChild(workElement);
var eventMouse = document.createEvent("MouseEvents");
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
workElement.dispatchEvent(eventMouse);
document.body.removeChild(workElement);
} else throw 'File saving not supported for this browser';
}
Notes, caveats, and weasel-words:
I have had success with this code in both Chrome and Firefox clients running in Linux (Maipo) and Windows (7 and 10) environments.
However, if sourceText is larger than a MB, Chrome sometimes (only sometimes) gets stuck in its own download without any failure indication; Firefox, so far, has not exhibited this behavior. The cause might be some blob limitation in Chrome. Frankly, I just don't know; if anybody has any ideas how to correct (or at least detect), please post. If the download anomaly occurs, when the Chrome browser is closed, it generates a diagnostic such as
This code is not compatible with Edge or Internet Explorer; I have not tried Opera or Safari.
StreamSaver is an alternative to save very large files without having to keep all data in the memory.In fact it emulates everything the server dose when saving a file but all client side with service worker.
You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream
There is a few example showcasing:
How to save multiple files as a zip
piping a readableStream from eg Response or blob.stream() to StreamSaver
manually writing to the writable stream as you type something
or recoding a video/audio
Here is an example in it's simplest form:
const fileStream = streamSaver.createWriteStream('filename.txt')
new Response('StreamSaver is awesome').body
.pipeTo(fileStream)
.then(success, error)
If you want to save a blob you would just convert that to a readableStream
new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference
Javascript has a FileSystem API. If you can deal with having the feature only work in Chrome, a good starting point would be: http://www.html5rocks.com/en/tutorials/file/filesystem/.
I need help. I have an angular app and by using DocRaptor want to generate PDF and save it as file. But I cant trigger the dialog to save file in Safari with any method what I have found on Stack Overflow. Those methods open file in current browser tab and replace site html or open file in new tab. No one cant shows the dialog. Here the examples what I have already tried to use. Environment MacOS - EL Capitan. Safari 9.0.3
Solution #1
var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
Example jsfiddle. Shows file in current tab. Replaces site. But works in Chrome.
Solution #2
<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Solution #3
<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>
and
$scope.saveJSON = function () {
$scope.toJSON = '';
$scope.toJSON = angular.toJson($scope.data);
var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',window.URL.createObjectURL(blob));
downloadLink.attr('download', 'fileName.json');
downloadLink[0].click();
};
Example Code Snippet. Shows the file content instead of document's html.
Solution #4
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
Example Code Snippet. Replace document with file content in Safari. Works in Chrome.
And similar Solution #5
function download(text, name, type) {
var a = document.createElement("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Also I have tried to use libraries like:
FileSaver - It opens file in Safari instead of document. So you should click Cmd+S. Example.
If we use type 'pplication/octet-stream' the name of file will be unknown or there was be an error 'Failed to load resource: Frame load interrupted'. Issue.
Second library Downloadify - doesnt work in Safari at all. Issue.
Angular library nw-fileDialog - instead of save as it shows choose file. Issue.
DocRaptor has own example with jQuery.
Example with angular in jsfiddle. It works in Chrome but in Safari example doesnt work be cause of error with SAMEORIGIN
Refused to display 'https://docraptor.com/docs' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
But if we reproduce it on server and change url on 'https://docraptor.com/docs.pdf' it works and open file in new tab and automatically download the file so you cant choose a folder and after download user see white empty screen tab in browser. If we specify form target="_self" it will work perfect, but console will have an error 'Failed to load resource:'.
I will appreciate any help with this problem.
Thanks.
Regards.
Try using Blob file for this:
// Buffer can be response from XMLHttpRequest/Ajax or your custom Int32 data
function download(buffer, filename) {
var file = new Blob([buffer], {
type: 'application/octet-stream' // Replace your mimeType if known
});
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var converted = e.target.result;
converted.name = filename;
converted.webkitRelativePath = filename;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = converted;
};
fileReader.onerror = function(e) {
throw new Error('Something is wrong with buffer data');
};
fileReader.file = file;
fileReader.readAsDataURL(file);
}
It basically uses filebuffer and download that as an iframe content. Make sure to hook correct mime type so that safari security system will recieved analyse filetype.
Ideally, Solution #2 would be the answer, but the download attribute does not yet have cross-browser support.
So you have to use a <form> to create the download. As you noted, DocRaptor's jQuery example uses this technique.
The SAMEORIGIN error is actually because JSFiddle is running the code in an iFrame with their origin settings. If you run this straight from your Angular application, you shouldn't have any problems.
I'm trying to find a cross browser way to store data locally in HTML5. I have generated a chunk of data in a Blob (see MDN). Now I want to move this Blob to the actual filesystem and save it locally. I've found the following ways to achieve this;
Use the <a download> attribute. This works only in Chrome currently.
Microsoft introduces a saveAs function in IE 10 which will achieve this.
Open the Blob URL in the browser and save it that way.
None of these seems to work in Safari though. While (1) works in Chrome, (2) in IE and (3) in Firefox no one works in Safari 6. The download attribute is not yet implemented and when trying to open a blob using the URL Safari complains that URLs starting with blob: are not valid URLs.
There is a good script that encapsulates (1) and (3) called FileSaver.js but that does not work using the latest Safari version.
Is there a way to save Blobs locally in a cross browser fashion?
FileSaver.js has beed updated recently and it works on IE10, Safari5+ etc.
See: https://github.com/eligrey/FileSaver.js/#supported-browsers
The file name sucks, but this works for me in Safari 8:
window.open('data:attachment/csv;charset=utf-8,' + encodeURI(csvString));
UPDATE: No longer working in Safari 9.x
The only solution that I have come up with is making a data: url instead. For me this looks like:
window.open("data:image/svg+xml," + encodeURIComponent(currentSVGString));
Here data is the array buffer data coming from response while making http rest call in js. This works in safari, however there might me some issue in filename as it comes to be untitled.
var binary = '';
var bytes = new Uint8Array(data);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
var base64 = 'data:' + contentType + ';base64,' + window.btoa(binary);
var uri = encodeURI(base64);
var anchor = document.createElement('a');
document.body.appendChild(anchor);
anchor.href = uri;
anchor.download = fileName;
anchor.click();
document.body.removeChild(anchor);
Have you read this article? http://updates.html5rocks.com/2012/06/Don-t-Build-Blobs-Construct-Them
Relating to http://caniuse.com/#search=blob, blobs are possible to use in safari.
You should consturct a servlet which delivers the blob via standard http:// url, so you can avoid using blob: url. Just make a request to that url and build your blob.
Afterwards you can save it in your filesystem or local storage.
The download attribute is supported since ~safari 10.1, so currently this is the way to go.
This is the only thing that worked for me on safari.
var newWindow = window.open();
const blobPDF = await renderMapPDF(); // Your async stuff goes here
if (!newWindow) throw new Error('Window could not be opened.');
newWindow.location = URL.createObjectURL(blobPDF);