Dynamically trigger download in Javascript for a newly created file (xlsx or docx) from Server to User

Viewed 76

In a web application I am working on, the frontend is html/css/js and the backend is python, which are linked using restful API.

In one of the process, I need the following:

  1. User click a button, which might be labeled as "generate xlsx and download"
  2. The javascript from frontend has a button event listener, and it goes off to tell backend python to generate an xlsx, then return (using node-fetch) to javascript the xlsx name and location
  3. Then, I create an <a> tag as code snippet below, to point href to where this new xlsx is generated

Step #1 & #2 worked perfectly fine. Then when it goes to step #3, the script below just not working. The code is ended up downloading an xlsx, which contains the whole html webpage ... (why would I need that ...), not the xlsx I assigned as href.

Please, will anyone be able to help me find a solution?

downloadFile: (fileLink, fileName) => {
       var el = document.createElement("a");
       el.setAttribute('download', "");
       el.href = fileLink;
       console.log(fileLink);

       document.body.appendChild(el);

       // Above code is equivalent to
       // <a href="path of file" download="file name"> 

       // onClick property, to trigger download
       el.click();
       el.remove();
}
1 Answers

Alright, I figured this out myself ...

It turned out the el.href = fileLink; makes the app thinks the fileLink sits on the web so it automatically adds relative path onto it. For instance, http://localhost:5000/fileLink. Then it could not find it.

To solve this, I need Nginx or flask to serve a repository from server then I will change the code to el.href = 'http://${webserverIP}/${fileLink}'; Then it will work.

Related