I have created a function to download the file, but the issue is it opens the file on the same tab, I a trying to force download this file in the system.
I read other threads but didn’t get the answer as I was expected and helpful.
Please help me create this function that downloads the file.
I have tried this code as below
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.click();
link.remove();
}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');
4
Answers
Seems like – as with normal links – you need to set the
target
attribute.Note: snippet won’t work here because popups are blocked. This means that it does work.
if you need to open it in new tab just add target attribute like below EX
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');
If you want to open the file in a new tab, you can simply add a
target="_blank"
attribute (link.setAttribute("target", "_blank");
).If you want to forcefully download the file instead of opening/previewing it in the browser, you can convert the file URI to a blob. For example:
JS Fiddle: https://jsfiddle.net/sh4dfm6a/
here is a typical js download function sample. In your code, firstly you should replace ‘name’ with name, using the variable given.
}
The reason why it only opens the PDF might be you are running your code locally, you could try to put it to your server and test.