React - Image URL을 다운로드 할 수 있는 방법

Moolbum·2023년 11월 19일
0

React

목록 보기
21/23
post-thumbnail

구현을 하고 싶은 형태

유저가 다운로드 버튼을 클릭할 시 서버에서 받은 이미지 URL을 파일로 저장!

구현 방법

다운로드 버튼은 공통적으로 많이 사용할 것 같아 utils 폴더의 downloadFile.ts에 작업했습니다.
이미지 URL과 fileName을 받도록 해서 fileName을 넘기지 않을 경우

공통적으로 download라는 파일명으로 저장이 됩니다.

downloadFile.ts

export const toDataURL = (url: string) => {
  return fetch(url)
    .then((response) => {
      return response.blob();
    })
    .then((blob) => {
      return URL.createObjectURL(blob);
    });
};

export const downloadFile = async (url: string, fileName?: string) => {
  const a = document.createElement("a");
  a.href = await toDataURL(url);
  a.download = fileName ?? "download";

  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

실제 사용

import { downloadFile } from "@/src/utils/downloadFile";


...
     <IconButton
         buttonSize={24}
         buttonColor="blue"
         buttonGrade="secondary"
          onClick={() => {
            downloadFile(item.mediaUrl, item.originalFileName);
          }}
        >
         다운로드
     </IconButton>
profile
Junior Front-End Developer 👨‍💻

0개의 댓글