feat: 공지사항등록 - 파일 다운로드 반영

main
minuk926 3 years ago
parent eb3733b24d
commit 68e8747a63

@ -12,20 +12,29 @@ import {
GET_FILE_DOWNLOAD GET_FILE_DOWNLOAD
} from 'commons/ApiUrl'; } from 'commons/ApiUrl';
import axios from 'utils/axios'; import axios from 'utils/axios';
import login from '../views/pages/authentication/authentication/Login'; import FileSaver from 'file-saver';
import { ACCESS_TOKEN_NAME } from '../commons/constants';
class OpstBizService { class OpstBizService {
// eslint-disable-next-line no-return-await // eslint-disable-next-line no-return-await
getComboCodeList = async (params) => await axios.get(GET_CMM_CODE_LIST, { params }); getComboCodeList = async (params) => await axios.get(GET_CMM_CODE_LIST, { params });
// TODO: 헤더에서 파일 정보 읽을 수 있도록 변경 필요 // TODO: 헤더에서 파일 정보 읽을 수 있도록 변경 필요
fileDownload = (id) => fileDownload = async (id, filename, alert) => {
axios.get(GET_FILE_DOWNLOAD + id, { await axios
responseType: 'blob' // 'arrayBuffer', .get(GET_FILE_DOWNLOAD + id, {
// withCredentials: process.env.NODE_ENV === 'development' responseType: 'blob' // 'arrayBuffer',
// headers: { Authorization: window.localStorage.getItem(ACCESS_TOKEN_NAME) } // withCredentials: process.env.NODE_ENV === 'development'
}); // headers: { Authorization: window.localStorage.getItem(ACCESS_TOKEN_NAME) }
})
// eslint-disable-next-line consistent-return
.then((res) => {
if (res.isAxiosError) {
alert.show('파일을 다운로드 할 수 없습니다[파일정보 오류]');
return false;
}
FileSaver.saveAs(res, filename);
});
};
setRowId = (params, idx) => { setRowId = (params, idx) => {
if (params && params.page && params.size) return params.page * params.size + idx + 1; if (params && params.page && params.size) return params.page * params.size + idx + 1;

@ -23,7 +23,7 @@ import 'assets/scss/style.scss';
// optional configuration // optional configuration
const options = { const options = {
position: positions.MIDDLE, // positions.BOTTOM_CENTER, position: positions.MIDDLE, // positions.BOTTOM_CENTER,
timeout: 3000, timeout: 2000,
type: types.INFO, // info / success / error type: types.INFO, // info / success / error
offset: '50px', offset: '50px',
transition: transitions.SCALE, // 'scale' / fade transition: transitions.SCALE, // 'scale' / fade

@ -26,21 +26,33 @@ const axiosService = axios.create({
*/ */
// const alertError = (config: AxiosRequestConfig, request: any, response: AxiosResponse, error: Error) => { // const alertError = (config: AxiosRequestConfig, request: any, response: AxiosResponse, error: Error) => {
const alertError = (config, request, response, error) => { const alertError = (config, request, response, error) => {
if (response && response.data) { if (response) {
const errCode = response.data.code || response.data.status; if (response.message) {
const errMsg = response.data.code !== '' && response.data.code !== null ? response.data.message : response.data.error; Swal.fire({
console.error(`${errCode}: ${errMsg}`); icon: 'error',
console.error('================================='); title: 'Api Error',
html: `${response.message}`,
// imageUrl:
timer: 5000
}).then((r) => r);
return;
}
if (response.data) {
const errCode = response.data.code || response.data.status;
const errMsg = response.data.code !== '' && response.data.code !== null ? response.data.message : response.data.error;
console.error(`${errCode}: ${errMsg}`);
console.error('=================================');
// Alert.error(`${errCode}: ${errMsg}`); // Alert.error(`${errCode}: ${errMsg}`);
Swal.fire({ Swal.fire({
icon: 'error', icon: 'error',
title: 'Api Error', title: 'Api Error',
html: `${errMsg} [ ${errCode} ]`, html: `${errMsg} [ ${errCode} ]`,
// imageUrl: // imageUrl:
timer: 5000 timer: 5000
}).then((r) => r); }).then((r) => r);
return; return;
}
} }
if (error.isAxiosError) { if (error.isAxiosError) {
@ -98,11 +110,12 @@ axiosService.interceptors.response.use(
// imageUrl: // imageUrl:
timer: 5000 timer: 5000
}).then((r) => r); }).then((r) => r);
console.log(response); // console.log(response);
} }
return Promise.resolve(response.data); return Promise.resolve(response.data);
}, },
({ config, request, response, ...error }) => { ({ config, request, response, ...error }) => {
Swal.close();
console.error('========== ApiService.response Error Data =========='); console.error('========== ApiService.response Error Data ==========');
alertError(config, request, response, error); alertError(config, request, response, error);
// error 데이타 return // error 데이타 return

@ -116,8 +116,6 @@ const PublicBoardForm = (props) => {
); );
const onChangeFile = (e) => { const onChangeFile = (e) => {
// console.log(e.target.files);
setSelectedFile(e.target.files[0].name); setSelectedFile(e.target.files[0].name);
setFilesInfo(e.target.files); setFilesInfo(e.target.files);
}; };
@ -127,50 +125,9 @@ const PublicBoardForm = (props) => {
alert.show('등록된 파일이 없습니다.'); alert.show('등록된 파일이 없습니다.');
return; return;
} }
setFileData(opstBizService.fileDownload(inCode)); opstBizService.fileDownload(inCode, inFilename, alert);
}; };
// TODO: :
useEffect(() => {
if (fileData) {
// const contentDisposition = fileData.headers['Content-Disposition']; //
// const fileName = 'unknown';Ï
// if (contentDisposition) {
// const [fileNameMatch] = contentDisposition.split(';').filter((str) => str.includes('filename'));
// if (fileNameMatch) [, fileName] = fileNameMatch.split('=');
// }
// fileName = JSON.stringify(fileData.headers).split('filename=')[1].split('",')[0];
FileSaver.saveAs(new Blob([fileData.data]), inFilename);
}
/*
if (fileData) {
// const contentDisposition = fileData.headers['Content-Disposition']; //
const fileName = 'unknown';
// if (contentDisposition) {
// const [fileNameMatch] = contentDisposition.split(';').filter((str) => str.includes('filename'));
// if (fileNameMatch) [, fileName] = fileNameMatch.split('=');
// }
// fileName = JSON.stringify(fileData.headers).split('filename=')[1].split('",')[0];
const url = window.URL.createObjectURL(new Blob([fileData.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
link.style.cssText = 'display:none';
link.setAttribute('id', 'tempLink');
document.body.appendChild(link);
link.click();
}
return () => {
const link = document.querySelector('#tempLink');
// eslint-disable-next-line no-unused-expressions
link && link.remove();
};
*/
}, [fileData]);
return ( return (
<> <>
<Grid container spacing={2}> <Grid container spacing={2}>

@ -1,94 +0,0 @@
import PropTypes from 'prop-types';
import React from 'react';
// material-ui
import { Button, CardContent, CardActions, Divider, Grid, IconButton, Modal, Typography } from '@mui/material';
// project imports
import MainCard from 'ui-component/cards/MainCard';
// assets
import CloseIcon from '@mui/icons-material/Close';
// generate random
function rand() {
return Math.round(Math.random() * 20) - 10;
}
// modal position
function getModalStyle() {
const top = 50 + rand();
const left = 50 + rand();
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`
};
}
const Body = React.forwardRef(({ modalStyle, handleClose }, ref) => (
<div ref={ref} tabIndex={-1}>
<MainCard
style={modalStyle}
sx={{
position: 'absolute',
width: { xs: 280, lg: 450 },
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)'
}}
title="Title"
content
secondary={
<IconButton onClick={handleClose} size="large">
<CloseIcon fontSize="small" />
</IconButton>
}
>
<CardContent>
<Typography variant="body1">Laboris non ad et aute sint aliquip mollit voluptate velit dolore magna fugiat ex.</Typography>
<Typography variant="body2" sx={{ mt: 2 }}>
Commodo amet veniam nostrud mollit quis sint qui nulla elit esse excepteur ullamco esse magna. Nisi duis aute est in mollit irure
enim tempor in.
</Typography>
</CardContent>
<Divider />
<CardActions>
<SimpleModal />
</CardActions>
</MainCard>
</div>
));
Body.propTypes = {
modalStyle: PropTypes.object,
handleClose: PropTypes.func
};
// ==============================|| SIMPLE MODAL ||============================== //
export default function SimpleModal() {
// getModalStyle is not a pure function, we roll the style only on the first render
const [modalStyle] = React.useState(getModalStyle);
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<Grid container justifyContent="flex-end">
<Button variant="contained" type="button" onClick={handleOpen}>
Open Modal
</Button>
<Modal open={open} onClose={handleClose} aria-labelledby="simple-modal-title" aria-describedby="simple-modal-description">
<Body modalStyle={modalStyle} handleClose={handleClose} />
</Modal>
</Grid>
);
}

@ -1,5 +1,4 @@
// project imports // project imports
import SimpleModal from './SimpleModal';
import ServerModal from './ServerModal'; import ServerModal from './ServerModal';
import MainCard from 'ui-component/cards/MainCard'; import MainCard from 'ui-component/cards/MainCard';
import SecondaryAction from 'ui-component/cards/CardSecondaryAction'; import SecondaryAction from 'ui-component/cards/CardSecondaryAction';

Loading…
Cancel
Save