버글버글

[React] axios로 pdf 다운로드 받기 본문

React/react 공부기록

[React] axios로 pdf 다운로드 받기

Bugle 2023. 5. 23. 17:49
반응형

 

1. axios 설치를 한다.

npm install axios

 

2. pdf 다운로드 할 button을 생성해준다.

  <button>다운로드</button>

 

3. event handler 추가

<button onClick={downloadPdf}>다운로드</button>

 

4. handler 정의하기

  const downloadPdf = () => {
    axios({
      url: 'PDF URL', // 다운로드할 PDF 파일의 URL
      method: 'GET',
      responseType: 'blob', // 응답 데이터는 Blob 형식
    })
      .then(response => {
        const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
        // 서버에서 받은 응답 데이터를 Blob 객체로 감싸고, 그 객체를 사용하여 다운로드할 수 있는 URL 생성

		const link = document.createElement('a');
        // 'a' 요소를 생성하여 link라는 이름의 상수에 할당 (이 요소는 다운로드 링크를 나타냄)
        
        link.href = downloadUrl;
        // 'a' 요소의 href 속성을 다운로드할 URL인 downloadUrl로 설정
        
        link.setAttribute('download', '성공.pdf');
        // 'a' 요소의 download 속성을 설정하여 파일 이름을 지정
        
        document.body.appendChild(link);
        // 'a' 요소를 문서의 본문(body)에 추가
        
        link.click();
        // 'a' 요소를 클릭하여 다운로드를 시작
        
        link.remove();
        // 'a' 요소를 문서에서 제거
      })
      .catch(error => {
        console.error('Error while downloading the PDF:', error);
      });
  }

 

5. 완성 화면

 

 

 

 

* 최종코드

import React from 'react';
import { Button } from '@mui/material';
import axios from 'axios';

function Test() {

  const downloadPdf = () => {
    axios({
      url: 'PDF URL',
      method: 'GET',
      responseType: 'blob',
    })
      .then(response => {
        const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.setAttribute('download', '성공.pdf');
        document.body.appendChild(link);
        link.click();
        link.remove();
      })
      .catch(error => {
        console.error('Error while downloading the PDF:', error);
      });
  }


  return (
    
	<button onClick={downloadPdf}>다운로드</button>

  );
}

export default Test;

 

 

 

* 응용 (미리보기)

import React from 'react';
import { Button } from '@mui/material';
import axios from 'axios';

function Test() {

  const viewerPdf = () => {
    axios
    .get('/경로/guide.pdf')
    .then(() => {
      const width = 900;
      const height = 700;
      const left = window.screenX + (window.outerWidth - width) / 2;
      const top = window.screenY + (window.outerHeight - height) / 2;
      // 팝업창 띄워서 미리보기
      window.open(
        "/경로/guide.pdf",
        "팝업창 이름",
        `width=${width},height=${height},left=${left},top=${top}`
      );
    })
    .catch((e) => {
      alert("실패!!!!!");
      console.log(e);
    })
  }

  return (

	<button onClick={viewerPdf}>미리보기</button>

  );
}

export default Test;
반응형