2017-03-25 137 views
2

我想進行跨域請求以從我的Java Web應用程序下載文件。我現在用的是CORS過濾器,並已列入我的部署描述符中的配置文件(web.xml):無法使用CORS下載文件

 <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> 

我在href屬性跨域網址:

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

現在,當我點擊鏈接,整個頁面被重定向並且文件被下載。我能知道我該如何實現這一點。 謝謝

回答

1

我以前遇到類似的問題。您將無法使用問題中提到的使用href屬性的GET請求來下載文件。 相反,您可以按建議的here提交嵌入到iframe中的表單,並將表單與您的文件ID一起作爲隱藏元素提交,並且應該觸發下載。所以,你的錨標記應爲:

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

現在通過你的fileid作爲參數的onclick JS功能,並定義它像這樣:

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(); 

} 

您可以按照單個或多個文件類似的方法。 同樣要添加你可以在你的web.xml中包含這個過濾器配置:

<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> 
+1

感謝您的回覆。如果它有效,我會盡量接受你的答案。 –

+1

這工作。真棒! –