Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- @redux-toolkit
- 자바스크립트#JS#slice#splice
- CSS
- redux상태유지
- Beesbeesbees
- 노드교과서
- https://dasima.xyz/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EC%A0%9C%EA%B3%B1-math-pow-%EA%B3%84%EC%82%B0/
- 헷갈린다~
- JS#3일차달리자#초반인데#시간금방~
- 자바스크립트#JS#var#let#const#undefined#null
- 내장고차함수
- children vs childrenNodes
- User Flow
- dom
- UX
- variable#function
- https://developer-talk.tistory.com/299
- slice/splice/split
- removeCookie
- react
- UI
- 자바스크립트#조건문#문자열
- cmarket
- https://www.daleseo.com/js-array-slice-splice/
- for~in/for~of
- 자바스크립트
- toString#String
- ㄷㅌ
- js
- https://lo-victoria.com/introduction-to-redux-toolkit-for-beginners
Archives
- Today
- Total
Daily Front_Minhhk
[React] 파일 다운로드 훅_blob filedown hook 본문
import { useState } from "react";
import useToast from "@/hooks/toast/useToast";
const useFileDownload = () => {
const toast = useToast();
const [isDownloading, setIsDownloading] = useState<boolean>(false); // 다운로드 상태 관리
//! 파일 미리보기
const handleFileView = (fileUrl: string) => {
if (!fileUrl) return console.error("파일이 없습니다");
window.open(fileUrl, "_blank");
};
//! 파일 다운로드
const handleFileDownload = async (fileUrl: string) => {
if (!fileUrl) {
console.error("파일이 없습니다");
return;
}
const encodedFileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
const decodedFileName = decodeURIComponent(encodedFileName); // 한글 디코딩
try {
toast("다운로드 진행중입니다.", "success");
setIsDownloading(true); // 다운로드 시작 상태
const response = await fetch(fileUrl);
const blob = await response.blob();
// Blob > fileDown 강제 다운로드
const link = document.createElement("a");
const blobUrl = URL.createObjectURL(blob);
link.href = blobUrl;
link.download = decodedFileName; // 디코딩된 파일명으로 다운로드
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl); // 메모리 정리
setIsDownloading(false); // 다운로드 완료 상태
} catch (err) {
toast("다운로드에 실패했습니다.", "warning");
setIsDownloading(false); // 실패시 상태 변경
console.error(err);
}
};
return { handleFileView, handleFileDownload, isDownloading };
};
export default useFileDownload;
- 사용 컴포넌트에서 훅으로 꺼내와서 링크
const { handleFileView, handleFileDownload, isDownloading } = useFileDownload();
const handleFileDown = (fileUrl : string) => {
// 다운받을 url 넣어서 사용ㄱㄱ
}
// handleFileView 마찬가지로
// return 하위에 로딩 표시 할려면 {isDownloading && <div>loading 알아서 사용</div>}
- toast 는 react-toast 를 훅으로 사용
'Code개발일지' 카테고리의 다른 글
[React] 로그인 시, 유입종류 브라우저&웹&모바일 로그 남기기 (1) | 2024.12.08 |
---|---|
[Git] ssh-key 여러개 사용 (0) | 2024.12.08 |
[vercel] react-vite vercel 간단 배포 (0) | 2024.12.08 |
[next.js] react-pdf__적용 (+ zoom in/out) (0) | 2024.05.14 |
[TanStack Query] isFetching vs isLoading (0) | 2024.02.25 |