skip to Main Content

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


  1. 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');
    Login or Signup to reply.
  2. 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');

    Login or Signup to reply.
  3. 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);
    }
    

    JS Fiddle: https://jsfiddle.net/sh4dfm6a/

    Login or Signup to reply.
  4. here is a typical js download function sample. In your code, firstly you should replace ‘name’ with name, using the variable given.

    function loadPdfFile(uri, pFileName) {
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    downloadLink.download = pFileName;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    

    }

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search