2016-08-03 1 views
1

PDF를 가져 오기 위해 API를 호출하고 responseType을 arraybuffer로 보내는 작은 스크립트를 만들었습니다. 이 사용PDF로 다운로드 할 때 Chrome에서 Blob 객체를 차단합니다.

나는 새로운 물방울을 만들고 내가하는 앵커 요소를 만들 다운로드하려면이 강제로 '응용 프로그램/PDF'

과 유형을 설정, 그것을 블롭을 통과하고 클릭합니다.

이것은 테스트 서버의 로컬 및 다른 브라우저에서 정상적으로 작동하지만 Chrome에서는 다운로드 막대에 실패 - 파일 없음이 표시됩니다.

API에 URL을 탭에 붙여넣고 원래 API 호출의 응답을 Blob에 전달할 수 있으므로 PDF를 사용할 수 있습니다.

샘플 코드

var fileName = 'dummyFilename-' + offerId + '.pdf'; 
var blob = new window.Blob([resData], { type: 'application/pdf' }); 

var anchorElement = document.createElement('a'); 
var url = window.URL.createObjectURL(blob); 

document.body.appendChild(anchorElement); 
anchorElement.id = 'anchorElement'; 
anchorElement.hidden = 'true'; 
anchorElement.href = url; 

if (typeof anchorElement.download !== 'undefined') { 
    anchorElement.download = fileName; 
} else { 
    anchorElement.target = '_blank'; 
} 

anchorElement.click(); 

답변

0

이 ... 항상 해키 조금있다 강제 : 당신이 그 기능을 실행하기 위해 클릭하는 HTML 요소가 링크 인 경우

, 당신은 시도 할 수 있습니다

당신이 원하는 경우

<a href="path/to/your/file.pdf" download>Download PDF</a> 

당신은 이름을 바꿀 수 있습니다 :

download 속성을 추가하려면 당신의 클릭 이벤트 처리기 이런 식으로 뭔가 보일 것
<a href="path/to/your/file.pdf" download="downloaded-pdf-name.pdf">Download PDF</a> 

당신이 download 속성이 작동하지 않습니다 다른 브라우저에서 그 일을하기 위해이 솔루션을 사용하는 경우, 그러나

document.getElementById('#download-pdf').onclick = function (event) { 
    if (!"download" in document.createElement("a")) { 
     // Download is NOT supported, the browser is probably not Chrome 
     // You don't want the native behaviour, which will probably open 
     // the PDF in another tab, so: 
     event.preventDefault(); 

     // TODO: Adapt your code to execute from here... 
    } 
} 

을, 그 download 검사 할 수있다 Firefox에서는 작동하지 않습니다. 해당 옵션이있는 경우 How to detect support for the HTML5 "download" attribute?

내가 HTTP 응답 헤더Content-Disposition = 'attachment; filename=downloaded-pdf-name.pdf'을 설정할 수 권합니다 : 여기에 대한 대답의 주석을 확인합니다. 다양한 백엔드에서 특정 방법을 보려면 here을 확인하십시오.

+0

실제로 나는 IE에서 다운로드 할 PDF를 얻는 데 BLOB 만 필요하다는 것을 실제로 발견했다. 결국 방금 클릭을 일반적인 URL로 지정하여 다운로드 속성을 설정하여이 기능을 지원하지 않는 브라우저에서 새 탭을 열도록했습니다. 나는 아직도 크롬이 Blob을 올바르게 처리하지 못하는 이유를 잘 모르고있다. –

0

시도해 보셨습니까? (요소를 만들지 않고) ... 도움이 되었으면 좋겠다.

var fileName = 'dummyFilename-' + offerId + '.pdf'; 
var blob = new window.Blob([resData], { type: 'application/pdf' }); 
// Parse blob object to base64 to prevent chrome blocking: 
var reader = new FileReader(); 
reader.readAsDataURL(blob); 
reader.onloadend = function() { 
    base64data = reader.result; 
    // For IE: 
    if (window.navigator && window.navigator.msSaveOrOpenBlob) { 
     window.navigator.msSaveOrOpenBlob(base64data); 
    } // For webkit 
    else { 
     var objectUrl = URL.createObjectURL(base64data); 
     window.open(objectUrl); 
    } 
}