3

I want to make a Cross-Domain request to download a file from my java web application. I am using the CORS filter and have included the configuration in my deployment descriptor(web.xml):

     <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
     </filter>
     <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   <filter>

I have the cross domain URL in the href attribute:

 <a href="http:localhost:8080/MyProject/downloadAction.action?fileId=1">download</a>

Now when I click the link, the whole page is redirected and the file is downloaded. Can I know what how can I achive this. Thanks

stefan_persie
  • 45
  • 2
  • 8
  • Does this answer your question? [Why does my http://localhost CORS origin not work?](https://stackoverflow.com/questions/10883211/why-does-my-http-localhost-cors-origin-not-work) – Liam Mar 26 '21 at 09:14

1 Answers1

2

I faced a similar problem sometime ago. You will not be able to download the file using a GET request using href attribute as u mentioned in the question. Instead you can submit a form embedded in an iframe as suggested here and submit the form with your file id as a hidden element and it should trigger the download. So your anchor tag shall be:

<a href="javascript:void(0)" onclick="downloadFile('+fileId+')">download</a>

Now pass your fileId as parameter to the onclick JS function and define it like this:

 function downloadFile(fileId) {
    let $iframe, iframeDoc, iframeHtml;

    if(($iframe = $('#download_frame')).length === 0) {
    $iframe = $('<iframe id="download_frame" +
                ' style="display: none;" src="about:blank"></iframe>'
               ).appendTo('body');
    }

    iframeDoc= $iframe[0].contentWindow;
    if (iframeDoc.document) {
     iframeDoc= iframeDoc.document;
    }

    iframeHtml= '<html><head></head><body><form method="POST" action="http:localhost:8080/MyProject/downloadAction.action"><input type="hidden" name="fileId" value="'+fileId+'"></form></body></html>'; 

    iframeDoc.open();
    iframeDoc.write(iframeHtml);

    $(iframeDoc).find('form').submit();

}

You can follow similar approach for single or multiple files. Also to add you can include this in ur web.xml in the filter configuration:

    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,X-Test-Header,Cache-Control
        </param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials
        </param-value>
    </init-param>
Community
  • 1
  • 1
Hasan K
  • 610
  • 8
  • 20