0

I have an api that returns this: enter image description here

it is supposed to be an apk file from the server. How can I achieve to do a react onClick and download the apk file? My current code looks like this, but it isn't working:

export function Download({}) {
  const [href, setHref] = useState('')

  useEffect(() => {
  (async () => {
    try {
      await userService.downloadMobileApp().then(response => {
        setHref(response)});
    }
    catch (e) {
      console.log(e);
      if(e.response === undefined){
        swal("Error!");
      }
      if (e.response.status == 401) {
        swal(e.response.data.message)
      }
      else {
        swal("Error!");
      }
    }
  })();
}, [])

  const downloadApp = async() => {
      const downloadLink = document.createElement("a");
      const fileName = 'randomAppName.apk';
      downloadLink.href = href;
      downloadLink.rel='noreferrer'
      downloadLink.download = fileName;
      console.log("downloadLink: ",downloadLink)
      downloadLink.click();
  }

  return <>
    <div >
      <Button  fillMode="outline" shape="rectangle" size="large"
            rounded="large" style={{ backgroundColor: "#c2183b", color: "white",fontWeight: "bold" }} 
             onClick={()=>downloadApp()}>Download</Button>
    </div>
  </>
};
OmarLittle
  • 423
  • 1
  • 9
  • 18
  • Does this answer your question? [Handle file download from ajax post](https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post) – jabaa Apr 27 '23 at 12:01
  • The important part in the answers is `a.href = window.URL.createObjectURL(xhttp.response);` – jabaa Apr 27 '23 at 12:03
  • @jabaa you mean add a.href = window.URL.createObjectURL(href); to my upper code, where href is the reponse? It doesn't work, it says: Argument 1 is not valid for any of the 1-argument overloads. Could it be that the response is not a valid file/blob? – OmarLittle Apr 27 '23 at 12:15
  • Not the whole response. Only data. – jabaa Apr 27 '23 at 15:51

1 Answers1

0

I think you are fetching a response, setHref the state. please try this code.

Check this site: https://roytuts.com/download-file-from-server-using-react/

const downloadApp = () => {

    fetch("your URL")

        .then(response => {

            response.blob().then(blob => {

                let url = window.URL.createObjectURL(blob);

                let a = document.createElement('a');

                a.href = url;

                a.download = 'employees.json';

                a.click();

            });

    });

}

Download