Home > other >  How to download files in javascript, It can be any type of file
How to download files in javascript, It can be any type of file

Time:02-01

I am getting file link from backend and I need to download the file directly or ask to savsAs on click a save button.

This is the link of one file.

https://unify.eoxyslive.com/images/jobs/image_2023_01_28T09_33_42_235Z.png

I have tried this method to download file and its downloading but its corrupted. and not opening.

const FileDownload = (link, fileName) => {
  fetch(link, { method: "get", mode: "no-cors", referrerPolicy: "no-referrer" })
    .then((res) => res.blob())
    .then((res) => {
      const aElement = document.createElement("a");
      aElement.setAttribute("download", fileName);
      const href = URL.createObjectURL(res);
      console.log(href);
      aElement.href = href;
      aElement.setAttribute("target", "_blank");
      // aElement.click();
      URL.revokeObjectURL(href);
    });
};

FileDownload("https://unify.eoxyslive.com/images/jobs/image_2023_01_28T09_33_42_235Z.png", "attachment.png")

CodePudding user response:

The easiest way to trigger a download is a download link, JavaScript-free.

<a href="file.ext" download>

(the attribute can also be used with a value, to suggest a filename other than the href)

But that can only do a simple GET request with no extra headers.

As soon as you need headers (for authentication, etc.), you will have to use fetch and create a download link (not a link with target=_blank as in your example ; that works but is inferior to download functionally and semantically) to a Blob URL.

A workaround for making download links work despite the need for headers (or another method than GET) is to have a Service Worker handle the extra headers transparently.

Also, if you have any control on the server, make it send a Content-Disposition: attachement response header. That will encourage the browser to trigger a download even with a normal link.

  • Related