Wednesday, December 30, 2020

React - axios api call to render file using blob - pdf or excel or xls or xlsx - using Asp.net

 I was struggling to call API to get PDF/Excel files. I found complete solution which is working in all browsers. Here is the .net c# code:


[Route("api/queries")]

    [HttpGet]

    public string getFile()

    {

        WebClient Client = new WebClient();

        Client.UseDefaultCredentials = true;

        byte[] myDataBuffer = Client.DownloadData("URL");

        string DocumentPath = Convert.ToBase64String(myDataBuffer);

        return DocumentPath;

    }


And here is front end in React using axios and blob:


axios.get(fetchFileUrl)

            .then((response) => {

                var raw = window.atob(response.data);

                var uint8Array = new Uint8Array(raw.length);

                for (var i = 0; i < raw.length; i++) {

                    uint8Array[i] = raw.charCodeAt(i);

                }

                var newBlob = new Blob([uint8Array])

                if (window.navigator && window.navigator.msSaveOrOpenBlob) {

                    window.navigator.msSaveOrOpenBlob(newBlob, fileName + '.xlsx');

                    console.log('ie', '11');

                }

                else {

                    const data = window.URL.createObjectURL(newBlob);

                    var link = document.createElement('a');

                    link.href = data;

                    link.download = fileName + '.xlsx';

                    link.click();

                    link.remove();

                    setTimeout(function () {

                        // For Firefox it is necessary to delay revoking the ObjectURL

                        window.URL.revokeObjectURL(data);

                    }, 100);

                    

                    console.log('not ie', 'others');

                   

                } 


                console.log('end', new Date().toLocaleDateString("en-US") + ' ' + new Date().toLocaleTimeString("en-US"));

            }).catch((error) => console.log(error));

No comments:

Post a Comment

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...