How to show download as prompt on new window from bootstrap model? - javascript

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

Related

Download PDF From Rest API

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

Image showing downloaded but not getting opened from browser when clicked

Image showing downloaded after i click on download image its showing Failed-No file in browser.I have done something wrong in providing download path may be. Here is my code:
<button id="download-button" class="btn--success">Download</button>
<script>
document.getElementById('download-button').addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('href', '/Downloads');
link.setAttribute('download', 'https://tinyjpg.com/images/social/website.jpg');
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
</script>
this final a tag should look like this:
<a href="https://tinyjpg.com/images/social/website.jpg" download>
<img src="https://tinyjpg.com/images/social/website.jpg">
</a>
but you set link
link.setAttribute('href', '/Downloads');
link.setAttribute('download', 'https://tinyjpg.com/images/social/website.jpg');
Try to create a downloadable link to achieve dynamically downloading functionality. For more reference refer createObjectURL
UPDATE
First, you need to convert the requested Image to base64 format
To achieve this, we need to download the requested image.
To download image, Implement Fetch and Promise together
After, Image get downloaded, convert it into blob res.blob()
FInally your code for dynamically creating link with little code change.
The entire code snippet is below
async function getBase64ImageFromUrl(imageUrl) {
var res = await fetch(imageUrl);
var blob = await res.blob();
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsDataURL(blob);
})
}
getBase64ImageFromUrl('https://cors-anywhere.herokuapp.com/'+'https://tinyjpg.com/images/social/website.jpg')
.then(function(result) {
var link = document.createElement('a')
link.href = result
link.style.display = 'none';
link.setAttribute('download','');
document.body.appendChild(link);
link.click();
document.body.removeChild(link)}
)
.catch(err => console.error(err));
Note - to avoid CORS issue, I have attached the 'https://cors-anywhere.herokuapp.com/' URL at the beginning of the image URL.
Try this instead
document.getElementById('download-button').addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('href', 'https://tinyjpg.com/images/social/website.jpg');
link.style.display = 'none';
link.setAttribute('download', '');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
The resulting a tag will be like this
<a href='https://tinyjpg.com/images/social/website.jpg' download style="display:none;" />
html download attribute will work, only those case when image and html file both are in same server . it means as per your image path your html file must be in https://tinyjpg.com/ server
you can update your script by this
document.getElementById('download-button').addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('href', 'https://tinyjpg.com/images/social/website.jpg');
link.setAttribute('download',"download");
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});

How to download a file programmatically using JS (Internet Explorer)

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

Excel export not working on Firefox but working fine in google crome

The below given event is called to export the data in the table into an EXCEL , The code works like a charm in Chrome . In IE and Firefox i am not getting anything(File, error etc).
Kindly assist me to go forward and export the file in all the browsers
$("[id$=myButtonControlID]").click(function(e) {
var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
var link = document.createElement("a");
link.download = "Reports";
link.href = result;
link.click();
});
With Firefox you have to explicitly add the link element to the DOM before you can execute .click():
$("[id$=myButtonControlID]").click(function(e) {
var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
var link = document.createElement("a");
document.body.appendChild(link); // You need to add this line
link.download = "Reports";
link.href = result;
link.click();
});
The data: URI is supported from IE8. But it "cannot be used for navigation [...]" so I assume it will not work in an <a href="...">. See this link.

Angularjs/Restangular, how to name file blob for download?

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/

Categories

Resources