skip to Main Content

I am calling API which give me below response

status  true
message "https://www.mywebsite.net/storage/pdf/15092023/1694768425.pdf"

and here is my react code to make to download

const downloadFile = async (file) => {
    const res = await customerServices.paymentInvoice( file );
    setTotalUrl(res.data);
    const fileName = /[^/]*$/.exec(file)[0];
    //const data = new Blob([res], { type:'application/pdf' });
    const link = document.createElement("a");
    link.href =res.data;
    link.setAttribute("download", fileName);
    link.setAttribute("id", "custom-file-click");
    link.setAttribute("target", "blank");
    document.body.appendChild(link)
;
    link.click();
  };

But it not downloading to file instead it is opening it in tab

2

Answers


  1. This issue might be related to the target attribute you set on the <a> element.

    Here’s how you can modify your code to ensure the file is downloaded:

    const downloadFile = async (file) => {
        const res = await customerServices.paymentInvoice(file);
        setTotalUrl(res.data);
        const fileName = /[^/]*$/.exec(file)[0];
        const link = document.createElement("a");
        link.href = res.data;
        link.setAttribute("download", fileName);
    
        // Remove the following line that sets the target attribute
        // link.setAttribute("target", "blank");
    
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // Clean up after the download
    };
    
    Login or Signup to reply.
  2. as this guy suggested in another post even if you add download attribute
    you need to add some permission in the backend so im assuming it might be a backend issue

    https://stackoverflow.com/a/6794317/18018440

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