How to download a file from database

First we have to define a function and then call the function on click. 

Below is an example of the downloading a file. 

 const onClickExport = async () => {
    const res = await webservice.get2(`/exportCountry`, {});
    if (res) {
      const url = window.URL.createObjectURL(new Blob([res]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `country_${moment().unix()}.xlsx`);
      document.body.appendChild(link);
      link.click();
    }
  };


Note: 

const get2 = (URL, params) => {
  const promise = instance2.get(URL, params);
  const dataPromise = promise.then((response) => response.data);
  return dataPromise;
};

 const instance2 = axios.create({
  baseURL: baseURL,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "SESSION-TOKEN": userData ? userData.token : "",
  },
  responseType: "blob",
});

 

Comments