Image showing downloaded but not getting opened from browser when clicked - javascript

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

Related

How to download PDF automatically on click instead of opening it in new tab using js?

I have an input URL with which I want to download pdf file directly without viewing it in a new tab or on the same tab, I have tried following things till now but nothing is helping. Frist tried with this
http.success(function (data) {
var link = document.createElement('a');
link.href = data.results[0].value.url;
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
This script is not downloading the file. It opens the file in the same tab.
Have tried all the answers in these previously answered questions. But nothing worked for me.
How can I download a pdf from a url using javascript?
How to download PDF automatically using js?
Download pdf without opening in browser
Then I tried with this Blob. Added the blob to my script and then tried again.
http.success(function (data) {
var blob=new Blob([data.results[0].value.url],{ type: "application/pdf" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
But this time it downloads the file. But can't able to open it. The downloaded file is corrupted.
Have tried the answers in these questions. But nothing worked for me.
PDF is corrupted after reconstructing it using URL.createObjectURL
Problem downloading a PDF blob in JavaScript
Blob from buffer returns corrupted pdf
please let me know if there are any other ways to download the pdf file directly. Thanks in advance.
What is stored in data.results[0].value.url?
Is it just a link to the PDF? If that's the case you will need to fetch the pdf document first.
Try this
http.success(function (data) {
fetch(data.results[0].value.url)
.then((response) => response.arrayBuffer())
.then((pdfFile) => {
const blob = new Blob([pdfFile], { type: "application/pdf" });
const anchor = document.createElement("a");
anchor.href = window.URL.createObjectURL(blob);
anchor.download = "SOME FILENAME.PDF";
// some browser needs the anchor to be in the doc
document.body.append(anchor);
anchor.click();
anchor.remove();
// in case the Blob uses a lot of memory
window.addEventListener(
"focus",
() => {
URL.revokeObjectURL(anchor.href);
},
{
once: true,
}
)
});
})
First, I would recommend trying the simplest example.
const pdfLink = data.results[0].value.url
const download = (url) => {
const link = document.createElement('a');
link.setAttribute('download', 'fileName.pdf');
link.setAttribute('href', url);
link.click();
}
downloadBlob = (blob) => download(URL.createObjectURL(blob))
fetch(pdfLink)
.then(response => response.blob())
.then(downloadBlob)
I share you a piece of code using MUI + JS
<IconButton variant="contained"
sx={{
fontSize: '1rem',
fontWeight: 'normal',
color:'silver',
}}
component='label'
size={'small'}
onClick={() => {
const url = 'https:.....'
fetch(url)
.then((res) => { return res.blob(); })
.then((data) => {
const a = document.createElement("a")
a.href = window.URL.createObjectURL(data)
a.download = formValues[id]
a.click()
});
}}>
<VisibilityIcon />
</IconButton>

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

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

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

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

Table to CSV without using download attribute as it is not supported on Safari browser

I am trying to export HTML table to CSV using JQuery.
I am able to export the data to CSV with below code,Succeeded in all browsers but not able to export in Safari(5.1.2) browser.
I tried with download attribute, but came to know Safari browser doesn't support download attribute.
Please let me know if there is work around?
var usersCSVData = [];
usersCSVData.push('LastName ','FirstName ', 'Login ','City ','State','Location ');
var fileName = "UserCSVdata.csv";
var buffer = usersCSVData.join("\n");
var blob = new Blob([buffer], {
"type": "text/csv;charset=utf8;"
});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, fileName);
}
else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style = "visibility:hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
I think this JavaScript library may be the solution you need:
https://github.com/eligrey/FileSaver.js
You will also need the blob.js dependency for Safari < 6.1

Categories

Resources