[TIL] javascript pdf 새탭 말고 강제로 파일 다운로드

Captainjack·2022년 4월 11일
0

TIL

목록 보기
147/258

구글링해도 로컬 환경에서 a 코드 download를 이용한 방법밖에 안나오는데


<a href="주소" download> 다운 </a>

이렇게 해도 새탭으로 열릴뿐 -_-

서버에 있는 파일 url 주소로 다운 받는 방식이없었다.

postman으로 직접 서버 pdf url을 get으로 쏴봤을 때, pdf 내용이 출력 되고있는걸 확인하고

fetch를 이용하여 Pdf를 가져오기로 결정

 <div style="display: flex; flex-direction: column; align-items: flex-start;">
   <a id="element-to-print-kr" >
     <span class="txt-hidden">한국어짱.pdf</span>
   </a>
</div>

 document.getElementById("element-to-print-kr").addEventListener("click", () => {
   pdf_file_get("서버 pdf url 주소", "kr");
 })
async function pdf_file_get(file_url, language) {
  const init = await fetch(file_url, {method: "get"})
  const blob = await init.blob()
  // use blob ... (await 키워드 사용)
  // *** 예제: 함수가 실행되면 파일 다운로드 바로 되게 ***
  // 파일이름 가져오기 [중간 단락 if문에 대한 부분 파일명을 자르는 것 같은데 pdf로는 테스트 안넘어가짐]
  const disposition = init.headers.get("content-disposition")
  let fileName = "information.pdf";
  if(language === "kr") {
    fileName = "한국어.pdf";

  if(disposition && disposition.indexOf('attachment') !== -1) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
    const matches = filenameRegex.exec(disposition)
    if (matches != null && matches[1]) {
      fileName = matches[1].replace(/['"]/g, '')
    } 
  }

  // 가상 링크 DOM 만들어서 다운로드 실행 [가상 돔으로만 a 태그 방식으로 만들려니까 안됨 ㅋㅋ]
  const url = URL.createObjectURL(await blob)
  const a = document.createElement("a")
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  window.URL.revokeObjectURL(url)
}

1분 컷일줄 알았던 고작 pdf 다운받게하기가 3시간의 삽질이 되어버림 ㅋ 무슨 라이브러리도 설치하고 아주개판 ㄱㅅ


출처

https://codesandbox.io/s/fetch-based-file-download-0kxod?file=/src/index.js:104-712

http://yoonbumtae.com/?p=2806

profile
til' CTF WIN

0개의 댓글