728x90
interface IDownloadExcelParams {
responseType?: ResponseType;
}
const fileAPI = {
downloadExcel: (params: IDownloadExcelParams) => {
return JSON.get(`file/excel`, params);
},
}
API μ μ λΆλΆ
const [isDownloading, setIsDownloading] = useState(false);
const downloadTemplate = async () => {
try {
setIsDownloading(true);
const response = await fileAPI.downloadExcel({
responseType: 'blob',
});
if (response.status === 200) {
const blob = new Blob([response.data]);
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(blob);
downloadLink.download = 'file_template.xlsx';
downloadLink.click();
} else {
throw new Error(`λ€μ΄λ‘λ μ€ν¨: ${response.status} ${response.statusText}`);
}
} catch (error) {
console.error(error);
} finally {
setIsDownloading(false);
}
};
response νμ
μ μ§μ νμ§ μμΌλ©΄ JSON νμμΌλ‘ μ²λ¦¬λμ΄ Excel νμΌμ΄ μμλ μ μλ€.
λ°λ©΄ μλ‘μ΄ μ½λμμλ response νμ
μ 'blob'μΌλ‘ μ€μ νμ¬ μ΄μ§ λ°μ΄ν°λ‘ μ²λ¦¬νλ©΄ μμ μμ΄ νμΌ λ€μ΄λ‘λκ° κ°λ₯νλ€.
isDownloading λ³μλ₯Ό λ§λ€μ΄μ€ μ΄μ λ λ€μ΄λ‘λ μνμΌ λ λ€μ΄λ‘λ λ²νΌμ ν΄λ¦νμ§ λͺ»νκ² νμ¬
μλμΉ μκ² λκ°μ νμΌμ΄ μ¬λ¬ κ° λ€μ΄λ‘λ λλ κ²μ λ§κΈ° μν¨μ΄λ€.
import { Button } from 'react-bootstrap';
...
<Button
type='button'
onClick={downloadTemplate}
disabled={isDownloading}
>
<FontAwesomeIcon icon={faDownload} /> {t('button.file.downloadTemplate')}
</Button>
JSXμμλ μ΄λ κ² μ¬μ©ν μ μλ€.
react-bootstrapμ Buttonμ μ¬μ©νμκ³ isDownloading μνμΌ λ disabled λκ² νμλ€.
728x90