2014-12-03 2 views
3

웹 서비스에서 파일을 다운로드하려고합니다. 파일을 다운로드하는 방법을 알기 위해 복잡한 메타 데이터를 서버에 전달해야합니다. 다음은 임 수 상록 브라우저에서이 작업을 수행하는 방법입니다 : 다운로드 속성이 IE에서 사용할 수 없습니다 물론 감각의IE 9+ 다운로드 속성 해결 방법

// i use angular but not important for this demo 
$http.post({ /* complex object */ }).then(xhr){ 

    // use download attribute 
    // http://davidwalsh.name/download-attribute 

    var hiddenElement = document.createElement('a'); 
    hiddenElement.href = 'data:attachment/csv,' + encodeURI(xhr.data); 
    hiddenElement.target = '_blank'; 
    hiddenElement.download = $scope.filename + '.csv'; 
    hiddenElement.click(); 
    hiddenElement.remove(); 
}); 

나는 게시 할 수 아니에요. 내가 전에 사용했던 해결 방법은 다음과 같습니다

$("body>#download_iFrame").remove(); 
$("body").append('<iframe name="downloadFrame" id="download_iFrame" style="display:none;" src="" />'); 
$("#form-download")[0].submit(); 

다음

<form target="downloadFrame" 
    action="'api/search/export/'" 
    id="form-download"></form> 

문제는 내가 그와 같은 개체를 전달할 수 없다 HTML에

. 물론 숨겨진 입력을 넣고 그 값을 직렬화 할 수는 있지만 객체가 좀 크고 문제가된다.

어떻게 해결할 수 있습니까?

답변

0

최신 브라우저에만 관심이 있다면 FileSaver.js을 사용해보십시오. IE10 +에서 실행될 때 navigator.msSaveOrOpenBlob을 사용합니다.

var xhr = new XMLHttpRequest(); 
xhr.open("GET", url, true); 
xhr.responseType = "blob"; 
xhr.onload = fuction (eventInfo) { 
    if (this.status == 200) { 
     var blob = this.response; 

     // FileSaver.js usage: 
     saveAs(blob, "filename.ext"); 

     // Or IE10+ specific: 
     navigator.msSaveOrOpenBlob(blob, "filename.ext"); 
    } 
}; 
xhr.send(); 
+3

그래, IE9 지원이 필요합니다. – amcdnl