1
votes

Java is using Apache POI to generate excel file and they are sending file as response with response header "content-disposition", "attachment;filename=FileEName.xls".

In UI I am doing an ajax call and getting the file type data. How can I make that file downloadable in the same tab?

2

2 Answers

0
votes

One way is to generate an anchor tag and set the href attribute to the end-point that returns the file data.

This allows the browser to correctly process the content-disposition header and so display the browser specific file-download dialog as expected.

0
votes

XHR request cant show the browser file download dialog, to do so you should save excel file in a temp directory, then return the file address from API controller. With the return value From API controller, just call Below Functions with TempName (return value from API controller)

        function getExcelFile(tempName) {
            var frmWindow = getIFrameWindow(tempName);
            var frm = frmWindow.document.getElementById("frmFile");
            frm.submit();
        }
        function getIFrameWindow(tempName) {
            // Remove the old iframe
            var oldIFrame = document.getElementById("fileFrame");
            if (oldIFrame) {
                document.body.removeChild(oldIFrame);
            }
            // Create a new iframe
            createFrame(tempName);
            var wnd = window.frames["fileFrame"];
            return wnd;
        }
        function createFrame(tempName) {
            var frame = document.createElement("iframe");
            frame.name = "fileFrame";
            frame.id = "fileFrame";

            document.body.appendChild(frame);
            generateIFrameContent(tempName);
            frame.style.width = "0px";
            frame.style.height = "0px";
            frame.style.border = "0px";
        }

        function generateIFrameContent(tempName) {
            var frameWindow = window.frames["fileFrame"];
            var content = "<form id='frmFile' method='get' enctype='application/data' action='/Temp/" + tempName + "'></form>";
            frameWindow.document.open();
            frameWindow.document.write(content);
            frameWindow.document.close();
        }