'How can I convert a Binary file to a normal file and download it?

I'm lookin for a solution to convert my Binary file (coming from my server) to a normal file and download it. This is my server response :

{
  "fileName": "1111.pdf",
  "binary" : "MyLongBInaryData" 
  }

The tricks here is : I don't know the type of file before download it, because it comes with response (1111.pdf, or myDoc.docx, etc..) so I want to be able to convert the binary data and download the specified file. I've tried this :

axios.get(`/MyBackendAPI`, {
        responseType: 'arraybuffer',
        headers: {
        'Content-Type': 'application/json',
        Accept: 'application/pdf',
        },
        })
        .then((response) => {
        const url = window.URL.createObjectURL(
                new Blob([response.data])
                    );
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'file.pdf'); //or any other extension
        document.body.appendChild(link);
        link.click();
                })
                .catch((error) => console.log(error));

But It download a empty pdf, and I want to check for type of file before any download to be sure that I will download the correct format. Any ideas please how to achieve this ? Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source