javascriptdownloadanchortitlecontent-disposition

JavaScript anchor file download - override file name from Content-Disposition header


As mentioned in the title, I'm using JS, an anchor URL, and a download attribute to get a file from an external system.

The problem is that I have to download it under a specific filename and the PDF file preview contains a Contain-Disposition header with the filename from the server. For Chrome, the title from that header has higher priority and I don't know how to customize the title or override that header title.

Is there any workaroud for this using only client-side JavaScript?


Solution

  • As suggested by @Dai in the comments, you can use an implementation similar to the following to override the file name in the Content-Disposition header:

    fetch("url_to_your_pdf_file.pdf")
      .then((response) => response.blob())
      .then((blob) => {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = "desired_filename.pdf";
        a.click();
        URL.revokeObjectURL(url);
      })
      .catch((error) => {
        console.error("Error fetching the PDF:", error);
      });
    
    

    The fetch function is part of pure JavaScript, you do not require any external libraries to use it.