구현을 하고 싶은 형태
유저가 다운로드 버튼을 클릭할 시 서버에서 받은 이미지 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>
'React' 카테고리의 다른 글
React - Lucide React, Radix Icon, 아이콘 컴포넌트처럼 사용하기 (0) | 2023.09.23 |
---|---|
React - Tab 컴포넌트 만들기 (0) | 2023.09.23 |
React - Portals 로 모달만들기 (0) | 2023.09.23 |
React - 합성 컴포넌트 적용해보기 (Modal) (0) | 2023.09.23 |
React - 스크롤 퍼센트 구하기 (0) | 2023.09.23 |