The expected functionality is: on button click, a PPT gets downloaded(this comes from a REST call from an external site), in the meantime when the PPT is getting downloaded, a loading gif should be shown in the page and it should be stopped after the PPT is downloaded.
I've tried setTimeout() function, but it doesn't seem to be working right in this case.
Is it possible to implement through jQuery or javascript? Any help would be appreciated!
My test code:
<img src="/_layouts/15/images/loading16.GIF" style="display: none;" id="img">
<input type="button" value="download" id="download">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/gitbrent/sprestlib#1.8.0/dist/sprestlib.min.js"></script>
<script>
$("#download").click(function(){
$("#img").css("display","");
sprLib.file('Doc/Presentation.pptx').get()
.then(function (blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", _fileName);
link.style = "visibility:hidden";
document.body.appendChild(link);
link.click();
setTimeout(function () { document.body.removeChild(link); }, 500);
}).then(function(){
$("#img").css("display","none");
});
})
</script>
Test result:
Related
I tried the dom-to-image library to download a set of HTML div. The "to-image" part worked just fine, but after the div was converted to an image, I want it also downloaded directly as an image. But I can't do that.
The dom-to-image docs said you can create an anchor element, and put the attributes there, and activate with the click() function:
let link = document.createElement('a');
link.download = 'my-image-name.png';
link.href = dataUrl;
link.click();
here is the example I made with svelte, it won't download, if I put the anchor as a child, I can't click the link. BUT, I can right-click and open in new tab or open image in new tab and also save image as. So I think there's no problem with the src/URL.
<script>
import domtoimage from 'dom-to-image'
let capture, display = false
function close() {
display = !display
document.querySelector(".image").remove()
}
function save() {
console.log("save")
display = !display
domtoimage.toPng(capture)
.then(function (dataUrl) {
let link = document.createElement('a');
link.download = 'my-image-name.jpeg';
link.href = dataUrl;
link.click(); //not working
let img = new Image();
img.src = dataUrl;
img.className = "image"
let show = document.querySelector(".show")
show.appendChild(link).appendChild(img);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
//no error logged
});
}
</script>
<div class="capture" bind:this={capture}>
<h1 >Hello World!</h1>
<p>
<!-- long text just for example -->
</p>
</div>
<button on:click={save}>
save
</button>
<div class="show" class:display={display}>
<button on:click={close}>
close
</button>
</div>
<style>
.capture {
background-color:cornflowerblue;
padding:1rem;
color:white
}
h1 {
background-color:lavender;
padding:1rem;
color:coral
}
.show {
position:absolute;
top:0;
width:100vw;
height:100vh;
background-color:rgba(0,0,0,0.5);
display:none;
}
.display {
display:block;
}
</style>
UPDATE
I recreate the code in codepen and it works, so it's a svelte problem? or just the svelte REPL environment problem? I need to implement in my own svelte environment later.
The REPL does some click/navigation interception. The given code should work in a real environment.
I'm attempting to trigger a PDF download when landing on a page with next.js. When doing so it's opening another tab with the PDF which i'm fine with, but i'd like to open the PDF on another tab. So I added it with link.target ="_blank" on page load, there are 2 PDF tabs that are open now.
I've attempted get only 1 tab with the PDF to open but I am unable to. Is this an issue with next.js? How can I get my function to only 1 PDF tab.
I think the issue may be related to the server side render? If so how can I only call this function once?
Here is my download file function:
function downloadFile(filePath) {
if(process.browser) {
var link = document.createElement('a');
link.href = filePath;
link.target = "_blank"
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
}
downloadFile("http://www.africau.edu/images/default/sample.pdf");
Here is my full next js page:
const Download= () => {
function downloadFile(filePath) {
if(process.browser) {
var link = document.createElement('a');
link.href = filePath;
link.target = "_blank"
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
}
downloadFile("http://www.africau.edu/images/default/sample.pdf");
return (
<Layout>
<div> download pdf</div>
</Layout>
);
};
export default Download;
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 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);
});
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);
}