관리 메뉴

Silver Library (Archived)

[React.js] How to let client user to download file? 본문

Face the fear, build the future/Library of Logging

[React.js] How to let client user to download file?

Chesed Kim 2022. 12. 7. 21:52
반응형

핵심 요소.

CORS policy, fetch, JavaScript, mutation

 

예시 코드.

fetch('https://cors-anywhere.herokuapp.com/' + fileURL, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/pdf',
    },
  })
  .then((response) => response.blob())
  .then((blob) => {
    // Create blob link to download
    const url = window.URL.createObjectURL(
      new Blob([blob]),
    );
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute(
      'download',
      `FileName.pdf`,
    );

    // Append to html link element page
    document.body.appendChild(link);

    // Start download
    link.click();

    // Clean up and remove the link
    link.parentNode.removeChild(link);
  });

CORS 양식의 headers 를 따로 명시해주고, 진행을 하면 된다고 하는데...

아무래도 blob 이나 herokuapp 를 보면 내부 브라우저 API 나 자체 JS가 아닌,

'외부' 에 의존을 해서 진행하는 모양새입니다. 

 

다만 html 쪽을 mutate 하는 것 까진 괜찮아 보입니다.

 

두번째 예시.

axios({
    url: 'http://api.dev/file-download', //your url
    method: 'GET',
    responseType: 'blob', // important
}).then((response) => {
    // create file link in browser's memory
    const href = URL.createObjectURL(response.data);

    // create "a" HTML element with href to file & click
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'file.pdf'); //or any other extension
    document.body.appendChild(link);
    link.click();

    // clean up "a" element & remove ObjectURL
    document.body.removeChild(link);
    URL.revokeObjectURL(href);
});

or

const FileDownload = require('js-file-download');

Axios({
  url: 'http://localhost/downloadFile',
  method: 'GET',
  responseType: 'blob', // Important
}).then((response) => {
    FileDownload(response.data, 'report.csv');
});

제법 재미나게 적고 있었는데 갑자기 제멋대로 날아가서...일단 링크와 요약으로 기록을 대체 해 둡니다.

 

요약하자면, 공통점이 있습니다.

- CORS policy

- JS 에서 html 쪽으로 연결 된 .click을 구현 해 두고,

- 다운로드 시행 후, 해당 링크가 사라지게 한다.

 

로 보여집니다.

다만 위 예시대로 하면 메모리 문제가 있어 보이니,

더 나은 방법은 향후 이 기능 구현 때 시험 해 보면서 알아봐야 겠습니다.

 

how to download file in react js

I receive file url as response from api. when user clicks on download button, the file should be downloaded without opening file preview in a new tab. How to achieve this in react js?

stackoverflow.com

 

How to download files using axios

I am using axios for basic http requests like GET and POST, and it works well. Now I need to be able to download Excel files too. Is this possible with axios? If so does anyone have some sample cod...

stackoverflow.com

 

 

How do I programmatically click a link with javascript?

Is there a way to click on a link on my page using JavaScript?

stackoverflow.com