For some reason this seems easier in IE than Chrome/FF:
$scope.download = function() {
Restangular.one(myAPI)
.withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {
//IE10 opens save/open dialog with filename.zip
window.navigator.msSaveOrOpenBlob(response, 'filename.zip');
//Chrome/FF downloads a file with random name
var url = (window.URL || window.webkitURL).createObjectURL(response);
window.location.href = url;
});
};
Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?
As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click
var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
Download attribute compatibility
Just use https://www.npmjs.com/package/angular-file-saver
Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/
Related
I have the following text that i get from java with a get request.
GET: http://localhost:8101/raportet/Cinema.jasper
%PDF-1.4
%âãÏÓ
3 0 obj
<</Filter/FlateDecode/Length 1644>>stream
xœ½œ]SÛF†ïý+ö2½ˆ²_úêUÝ`Rh;étz¡`aDü‘H†ß•Ç
8ïJø5ã³ ôé<^Yþ<ø}20‘ˆÃHL¦ƒÑdð×#‹ãê·JH÷¨¾Ç©“ÅàÕ¡JŠÉåàÅ
..............
I want to download this file in frontend using js.
I tried a lot of methods but i cannot download it. Is there any method i can do it.
I've almost the same problem as this: Opening PDF String in new window with javascript
you can use this method if you want to show and download PDF in ReactJs
axios.get(exportUrl, {responseType:'blob'})
.then(response => {
// Create blob link to download
var blob = new Blob([response.data], { type: 'application/pdf' });
var URL = window.URL || window.webkitURL;
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.target = '_blank';
link.href = url;
link.setAttribute( //if you just want to preview pdf and dont want download delete this three lines
'download',
`Factor.pdf`,
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
link.parentNode.removeChild(link);
URL.revokeObjectURL(url);
})
}
For a project I need to save some text into a word document. I do this using this function:
function saveText(text) {
var data = new Blob([text], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
However, there is one problem. Whenever I try to open it it shows this error message:
The file is corrupt and cannot be opened.
(Sorry I couldn't embed the image; I don't have enough reputation yet)
So, I have a feeling that the problem is that I need to format my text differently because right now I am just calling the function like this: saveText("Test");. In an rtf file it does have lots of stuff at the start so I thought maybe word needs this as well. However, I have looked a lot 'round the internet and couldn't find a solution. Thanks for taking the time to read (and maybe answer) this :D
function saveText(text) {
var data = new Blob([text], {type: 'application/msword'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
I simply changed application/vnd.openxmlformatsofficedocument.wordprocessingml.document to application/ms-word and everything worked :)
For a normal HTML page I tried the below code which starts download in a separate window. When I use the same code for bootstrap modal form then it's not working. What else I need to do for implement same functionality in bootstrap modal ?
var newwin=window.open("",'newwindow','width=700,height=700, left=100,top=100,resizable=yes','_blank').document;
var link =newwin.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
you have used blob in window.URL.createObjectURL, which is undefined.
you can use this solution.
use code like this :
var newwin=window.open("",'newwindow','width=700,height=700, left=100,top=100,resizable=yes','_blank').document;
var link =newwin.createElement('a');
var blob = new Blob([json], {type: "octet/stream"});
link.href = window.URL.createObjectURL(blob);
link.download = fileName
window.location.assign(url);
I have a web page where there is a button that when clicked, generates a (by doing a conversion from json) csv file that is downloaded by the browser. It essentially uses the logic from this jsfiddle. This all works in chrome, but in IE, nothing happens.
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
The issue seems to be that the download attribute of an anchor tag doesn't exist in Internet Explorer. I've been looking at numerous articles and SO posts, but I haven't found a coherent solution that I can use in the page.
How can the code from the jsfiddle be implemented in IE?
This is what I have used in the past. This handles IE and non-IE.
var filename = "file.txt";
var data = "some data";
var blob = new Blob([data], { type: 'text/csv' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
The following code work perfectly in Chrome
<script>
function myFunction() {
var blob = new Blob(['<a id="a"><b id="b">hey!</b></a>'], {type : 'text/html'});
var newurl = window.URL.createObjectURL(blob);
document.getElementById("myFrame").src = newurl;
}
</script>
But it is not working with IE. Can some one please tell me what is wrong here.
The iframe "src" also set to the blob as shown below.
<iframe id="myFrame" src="blob:0827B944-D600-410D-8356-96E71F316FE4"></iframe>
Note:
I went on the window.navigator.msSaveOrOpenBlob(newBlob) path as well but no luck so far.
According to http://caniuse.com/#feat=datauri IE 11 has only got partial support for Data URI's. It states support is limited to images and linked resources like CSS or JS, not HTML files.
Non-base64-encoded SVG data URIs need to be uriencoded to work in IE and Firefox as according to this specification.
An example I did for Blob as a source of iFrame and working great with one important CAUTION / WARNING:
const blobContent = new Blob([getIFrameContent()], {type: "text/html"});
var iFrame = document.createElement("iframe");
iFrame.src = URL.createObjectURL(blobContent);
parent.appendChild(iFrame);
iFrame with Blob is not auto redirect protocol, meaning, having <script src="//domain.com/script.js"</script> inside the iframe head or body won't load the JS script at all even on Chrome 61 (current version).
it doesn't know what to do with source "blob" as protocol. this is a BIG warning here.
Solution: This code will solve the issue, it runs mostly for VPAID ads and working for auto-protocol:
function createIFrame(iframeContent) {
let iFrame = document.createElement("iframe");
iFrame.src = "about:blank";
iFrameContainer.innerHTML = ""; // (optional) Totally Clear it if needed
iFrameContainer.appendChild(iFrame);
let iFrameDoc = iFrame.contentWindow && iFrame.contentWindow.document;
if (!iFrameDoc) {
console.log("iFrame security.");
return;
}
iFrameDoc.write(iframeContent);
iFrameDoc.close();
}
I've run into the same problem with IE. However, I've been able to get the download/save as piece working in IE 10+ using filesaver.js.
function onClick(e) {
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"});
saveAs(blob, fileName);
e.preventDefault();
return false;
};
$('#download').click(onClick);
See http://jsfiddle.net/o0wk71n2/ (based on answer by #kol to JavaScript blob filename without link)