Home > other >  Download File through JavaScript
Download File through JavaScript

Time:08-07

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

CodePudding user response:

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.

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = 'name';
  link.href = uri;
  link.setAttribute("target", "_blank");
  link.click();
  link.remove();
}

downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');

CodePudding user response:

if you need to open it in new tab just add target attribute like below EX

function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.target = "_blank";
link.click();
link.remove();}

downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');

CodePudding user response:

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:

async function downloadURI(uri, name) {
  const link = document.createElement("a");
  link.download = name;
  const data await = fetch(uri).then((res) => res.blob())
  link.href = window.URL.createObjectURL(
    new Blob([data], { type: 'application/pdf' })
  );
  link.click();
  link.remove();
  window.URL.revokeObjectURL(link.href);
}
  • Related