- 파일 저장 공통 코드 적용
- 파일 삭제 기능 추가 - 다국어 적용
This commit is contained in:
parent
eeb2ba6c17
commit
57ce17a932
@ -3,6 +3,7 @@
|
||||
import fs from 'fs/promises'
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { writeImage, writeImageBuffer } from '@/lib/fileAction'
|
||||
|
||||
export async function GET(req) {
|
||||
const path = 'public/plan-map-images'
|
||||
@ -15,14 +16,7 @@ export async function GET(req) {
|
||||
const response = await fetch(decodeUrl)
|
||||
const data = await response.arrayBuffer()
|
||||
const buffer = Buffer.from(data)
|
||||
|
||||
try {
|
||||
await fs.readdir(path)
|
||||
} catch {
|
||||
await fs.mkdir(path)
|
||||
} finally {
|
||||
await fs.writeFile(`${path}/${fileNm}.png`, buffer)
|
||||
}
|
||||
await writeImage(fileNm, buffer)
|
||||
|
||||
return NextResponse.json({ fileNm: `${fileNm}.png` })
|
||||
}
|
||||
|
||||
@ -3,23 +3,25 @@
|
||||
import fs from 'fs/promises'
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { writeImage } from '@/lib/fileAction'
|
||||
|
||||
export async function POST(req) {
|
||||
const path = 'public/plan-bg-images'
|
||||
|
||||
const formData = await req.formData()
|
||||
const file = formData.get('file')
|
||||
const fileName = formData.get('fileName')
|
||||
const arrayBuffer = await file.arrayBuffer()
|
||||
const buffer = Buffer.from(arrayBuffer)
|
||||
// const buffer = new Uint8Array(arrayBuffer)
|
||||
await writeImage(fileName, buffer)
|
||||
// try {
|
||||
// await fs.readdir(path)
|
||||
// } catch {
|
||||
// await fs.mkdir(path)
|
||||
// } finally {
|
||||
// await fs.writeFile(`${path}/${fileName}`, buffer)
|
||||
// }
|
||||
|
||||
try {
|
||||
await fs.readdir(path)
|
||||
} catch {
|
||||
await fs.mkdir(path)
|
||||
} finally {
|
||||
await fs.writeFile(`${path}/${file.name}`, buffer)
|
||||
}
|
||||
|
||||
return NextResponse.json({ fileNm: `${file.name}` })
|
||||
return NextResponse.json({ fileNm: `${fileName}` })
|
||||
}
|
||||
|
||||
@ -22,18 +22,20 @@ export default function ImgLoad() {
|
||||
setMapPositionAddress,
|
||||
handleFileDelete,
|
||||
handleMapImageDown,
|
||||
handleAddressDelete,
|
||||
} = useRefFiles()
|
||||
const { currentCanvasPlan } = usePlan()
|
||||
const { getMessage } = useMessage()
|
||||
const { floorPlanState, setFloorPlanState } = useContext(FloorPlanContext)
|
||||
|
||||
const handleModal = () => {
|
||||
console.log(floorPlanState)
|
||||
setFloorPlanState({ ...floorPlanState, refFileModalOpen: false })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
console.log('🚀 ~ ImgLoad ~ floorPlanState.refFileModalOpen:', floorPlanState.refFileModalOpen)
|
||||
console.log('🚀 ~ ImgLoad ~ currentCanvasPlan:', currentCanvasPlan)
|
||||
// console.log('🚀 ~ ImgLoad ~ floorPlanState.refFileModalOpen:', floorPlanState.refFileModalOpen)
|
||||
// console.log('🚀 ~ ImgLoad ~ currentCanvasPlan:', currentCanvasPlan)
|
||||
}, [floorPlanState.refFileModalOpen])
|
||||
|
||||
useEffect(() => {
|
||||
@ -50,7 +52,7 @@ export default function ImgLoad() {
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<div className="img-flex-box">
|
||||
<span className="normal-font mr10">サイズ調整と回転</span>
|
||||
<span className="normal-font mr10">{getMessage('modal.image.load.size.rotate')}</span>
|
||||
<label className="toggle-btn">
|
||||
<input
|
||||
type="checkbox"
|
||||
@ -64,13 +66,13 @@ export default function ImgLoad() {
|
||||
<div className="img-load-item">
|
||||
<div className="d-check-radio pop">
|
||||
<input type="radio" name="radio03" id="ra06" value={'1'} onChange={(e) => handleRefFileMethod(e)} checked={refFileMethod === '1'} />
|
||||
<label htmlFor="ra06">ファイルを読み込む</label>
|
||||
<label htmlFor="ra06">{getMessage('common.input.file')}</label>
|
||||
</div>
|
||||
<div className="img-flex-box">
|
||||
<div className="img-edit-wrap">
|
||||
<label className="img-edit-btn" htmlFor="img_file">
|
||||
<span className="img-edit"></span>
|
||||
ファイルの追加
|
||||
{getMessage('common.load')}
|
||||
</label>
|
||||
<input
|
||||
type="file"
|
||||
@ -82,10 +84,10 @@ export default function ImgLoad() {
|
||||
<div className="img-name-wrap">
|
||||
{/* <input type="text" className="input-origin al-l" defaultValue={'IMG_Name.PNG'} readOnly />
|
||||
<button className="img-check"></button> */}
|
||||
{currentCanvasPlan?.bgImageName === null ? (
|
||||
<input type="text" className="input-origin al-l" value={refImage ? refImage.name : ''} readOnly />
|
||||
{!currentCanvasPlan?.bgImageName ? (
|
||||
<input type="text" className="input-origin al-l" value={refImage ? 'ref' + refImage.name : ''} readOnly />
|
||||
) : (
|
||||
<input type="text" className="input-origin al-l" value={currentCanvasPlan?.bgImageName} readOnly />
|
||||
<input type="text" className="input-origin al-l" value={'bg' + currentCanvasPlan?.bgImageName} readOnly />
|
||||
)}
|
||||
{(refImage || currentCanvasPlan?.bgImageName) && <button className="img-check" onClick={handleFileDelete}></button>}
|
||||
</div>
|
||||
@ -94,7 +96,7 @@ export default function ImgLoad() {
|
||||
<div className="img-load-item">
|
||||
<div className="d-check-radio pop">
|
||||
<input type="radio" name="radio03" id="ra07" value={'2'} onChange={(e) => handleRefFileMethod(e)} checked={refFileMethod === '2'} />
|
||||
<label htmlFor="ra07">アドレスを読み込む</label>
|
||||
<label htmlFor="ra07">{getMessage('common.input.address.load')}</label>
|
||||
</div>
|
||||
<div className="img-flex-box for-address">
|
||||
<input
|
||||
@ -106,18 +108,21 @@ export default function ImgLoad() {
|
||||
onChange={(e) => setMapPositionAddress(e.target.value)}
|
||||
/>
|
||||
<div className="img-edit-wrap">
|
||||
<button className="img-edit-btn" onClick={refFileMethod === '2' ? handleMapImageDown : () => {}}>
|
||||
完了
|
||||
<button
|
||||
className={`img-edit-btn ${mapPositionAddress.trim().length === 0 ? 'no-click' : ''}`}
|
||||
onClick={refFileMethod === '2' ? handleMapImageDown : () => {}}
|
||||
>
|
||||
{getMessage('common.finish')}
|
||||
</button>
|
||||
</div>
|
||||
{mapPositionAddress && <span className="check-address fail"></span>}
|
||||
{mapPositionAddress && <button className="check-address fail" onClick={handleAddressDelete}></button>}
|
||||
{/* <span className="check-address success"></span> */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid-btn-wrap">
|
||||
<button className="btn-frame modal act" onClick={handleModal}>
|
||||
完了
|
||||
{getMessage('common.finish')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -5,7 +5,7 @@ import { v4 as uuidv4 } from 'uuid'
|
||||
import { useSwal } from '@/hooks/useSwal'
|
||||
import { useAxios } from '../useAxios'
|
||||
import { currentCanvasPlanState } from '@/store/canvasAtom'
|
||||
import { convertDwgToPng, writeImageBuffer } from '@/lib/fileAction'
|
||||
import { convertDwgToPng, removeImage, writeImageBuffer } from '@/lib/fileAction'
|
||||
|
||||
export function useRefFiles() {
|
||||
const converterUrl = process.env.NEXT_PUBLIC_CONVERTER_API_URL
|
||||
@ -19,17 +19,51 @@ export function useRefFiles() {
|
||||
const { get, promisePut, promisePost } = useAxios()
|
||||
// const { currentCanvasPlan, setCurrentCanvasPlan } = usePlan()
|
||||
|
||||
useEffect(() => {
|
||||
console.log('refImage', refImage)
|
||||
}, [refImage])
|
||||
|
||||
useEffect(() => {
|
||||
if (refFileMethod === '1') {
|
||||
// 파일 불러오기
|
||||
setMapPositionAddress('')
|
||||
} else {
|
||||
setRefImage(null)
|
||||
}
|
||||
}, [refFileMethod])
|
||||
/**
|
||||
* 파일 불러오기 버튼 컨트롤
|
||||
* @param {*} file
|
||||
*/
|
||||
const handleRefFile = (file) => {
|
||||
setRefImage(file)
|
||||
console.log('handleRefFile', file)
|
||||
console.log('refImage', refImage)
|
||||
if (file && ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/gif'].includes(file.type)) {
|
||||
// setRefImage(file)
|
||||
file.name.split('.').pop() === 'dwg' ? handleUploadConvertRefFile(file) : handleUploadImageRefFile(file)
|
||||
} else {
|
||||
swalFire({
|
||||
text: '이미지가 아닙니다.',
|
||||
type: 'alert',
|
||||
icon: 'error',
|
||||
})
|
||||
}
|
||||
if (refImage) {
|
||||
swalFire({
|
||||
text: '파일을 변경하시겠습니까?',
|
||||
type: 'confirm',
|
||||
confirmFn: () => {
|
||||
setRefImage(file)
|
||||
file.name.split('.').pop() === 'dwg' ? handleUploadConvertRefFile(file) : handleUploadImageRefFile(file)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 확장자가 dwg일 경우 변환하여 이미지로 저장
|
||||
* 파일 확장자가 이미지일 경우 이미지 저장
|
||||
*/
|
||||
file.name.split('.').pop() === 'dwg' ? handleUploadConvertRefFile(file) : handleUploadImageRefFile(file)
|
||||
|
||||
// handleUploadRefFile(file)
|
||||
}
|
||||
|
||||
@ -37,15 +71,34 @@ export function useRefFiles() {
|
||||
* 파일 삭제
|
||||
*/
|
||||
const handleFileDelete = () => {
|
||||
setRefImage(null)
|
||||
setCurrentCanvasPlan((prev) => ({ ...prev, bgFileName: null }))
|
||||
swalFire({
|
||||
text: '삭제하시겠습니까?',
|
||||
type: 'confirm',
|
||||
confirmFn: () => {
|
||||
setRefImage(null)
|
||||
setCurrentCanvasPlan((prev) => ({ ...prev, bgFileName: null }))
|
||||
removeImage(currentCanvasPlan.id).then((res) => {
|
||||
console.log(res)
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 주소 삭제
|
||||
*/
|
||||
const handleAddressDelete = () => {
|
||||
setCurrentCanvasPlan((prev) => ({ ...prev, mapPositionAddress: null }))
|
||||
swalFire({
|
||||
text: '삭제하시겠습니까?',
|
||||
type: 'confirm',
|
||||
confirmFn: () => {
|
||||
setMapPositionAddress('')
|
||||
setCurrentCanvasPlan((prev) => ({ ...prev, mapPositionAddress: null }))
|
||||
removeImage(currentCanvasPlan.id).then((res) => {
|
||||
console.log(res)
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@ -56,9 +109,10 @@ export function useRefFiles() {
|
||||
return
|
||||
}
|
||||
|
||||
const res = await get({ url: `http://localhost:3000/api/html2canvas?q=${queryRef.current.value}&fileNm=${uuidv4()}&zoom=20` })
|
||||
console.log('🚀 ~ handleMapImageDown ~ res:', res)
|
||||
setCurrentCanvasPlan((prev) => ({ ...prev, bgImageName: res.fileNm, mapPositionAddress: queryRef.current.value }))
|
||||
const res = await get({ url: `http://localhost:3000/api/html2canvas?q=${queryRef.current.value}&fileNm=${currentCanvasPlan.id}&zoom=20` })
|
||||
// console.log('🚀 ~ handleMapImageDown ~ res:', res)
|
||||
console.log('currentCanvasPlan', currentCanvasPlan)
|
||||
setCurrentCanvasPlan((prev) => ({ ...prev, bgImageName: currentCanvasPlan.id, mapPositionAddress: queryRef.current.value }))
|
||||
}
|
||||
|
||||
/**
|
||||
@ -66,9 +120,10 @@ export function useRefFiles() {
|
||||
* @param {*} file
|
||||
*/
|
||||
const handleUploadImageRefFile = async (file) => {
|
||||
console.log('🚀 ~ handleUploadImageRefFile ~ file:', file)
|
||||
// console.log('🚀 ~ handleUploadImageRefFile ~ file:', file)
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('fileName', currentCanvasPlan.id)
|
||||
|
||||
const response = await fetch('http://localhost:3000/api/image-upload', {
|
||||
method: 'POST',
|
||||
@ -76,7 +131,8 @@ export function useRefFiles() {
|
||||
})
|
||||
|
||||
const result = await response.json()
|
||||
console.log('🚀 ~ handleUploadImageRefFile ~ res:', result)
|
||||
setRefImage(file)
|
||||
// console.log('🚀 ~ handleUploadImageRefFile ~ res:', result)
|
||||
// writeImageBuffer(file)
|
||||
}
|
||||
|
||||
@ -92,6 +148,7 @@ export function useRefFiles() {
|
||||
.then((res) => {
|
||||
convertDwgToPng(res.data.Files[0].FileName, res.data.Files[0].FileData)
|
||||
swalFire({ text: '파일 변환 성공' })
|
||||
setRefImage(res.data.Files[0].FileData)
|
||||
})
|
||||
.catch((err) => {
|
||||
swalFire({ text: '파일 변환 실패', icon: 'error' })
|
||||
@ -110,7 +167,7 @@ export function useRefFiles() {
|
||||
* 현재 플랜이 변경되면 플랜 상태 저장
|
||||
*/
|
||||
useEffect(() => {
|
||||
console.log('🚀 ~ useRefFiles ~ currentCanvasPlan:', currentCanvasPlan)
|
||||
// console.log('🚀 ~ useRefFiles ~ currentCanvasPlan:', currentCanvasPlan)
|
||||
// const handleCurrentPlan = async () => {
|
||||
// await promisePut({ url: '/api/canvas-management/canvas-statuses', data: currentCanvasPlan }).then((res) => {
|
||||
// console.log('🚀 ~ awaitpromisePut ~ res:', res)
|
||||
|
||||
@ -6,6 +6,7 @@ import { useAxios } from '@/hooks/useAxios'
|
||||
import { useMessage } from '@/hooks/useMessage'
|
||||
import { useSwal } from '@/hooks/useSwal'
|
||||
import { SAVE_KEY } from '@/common/common'
|
||||
import { readImage } from '@/lib/fileAction'
|
||||
|
||||
export function usePlan() {
|
||||
const [planNum, setPlanNum] = useState(0)
|
||||
@ -204,6 +205,7 @@ export function usePlan() {
|
||||
userId: userId,
|
||||
imageName: 'image_name', // api 필수항목이여서 임시로 넣음, 이후 삭제 필요
|
||||
objectNo: currentCanvasPlan.objectNo,
|
||||
mapPositionAddress: currentCanvasPlan.mapPositionAddress,
|
||||
canvasStatus: canvasToDbFormat(canvasStatus),
|
||||
}
|
||||
await promisePost({ url: '/api/canvas-management/canvas-statuses', data: planData })
|
||||
@ -233,6 +235,7 @@ export function usePlan() {
|
||||
const putCanvasStatus = async (canvasStatus) => {
|
||||
const planData = {
|
||||
id: currentCanvasPlan.id,
|
||||
mapPositionAddress: currentCanvasPlan.mapPositionAddress,
|
||||
canvasStatus: canvasToDbFormat(canvasStatus),
|
||||
}
|
||||
await promisePut({ url: '/api/canvas-management/canvas-statuses', data: planData })
|
||||
@ -285,6 +288,7 @@ export function usePlan() {
|
||||
updateCurrentPlan(newCurrentId)
|
||||
}
|
||||
}
|
||||
|
||||
const updateCurrentPlan = (newCurrentId) => {
|
||||
setPlans((plans) =>
|
||||
plans.map((plan) => {
|
||||
@ -295,8 +299,13 @@ export function usePlan() {
|
||||
useEffect(() => {
|
||||
setCurrentCanvasPlan(plans.find((plan) => plan.isCurrent) || null)
|
||||
setSelectedPlan(plans.find((plan) => plan.isCurrent))
|
||||
// setBgImage()
|
||||
}, [plans])
|
||||
|
||||
const setBgImage = () => {
|
||||
readImage(selectedPlan?.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* 새로운 plan 생성
|
||||
* 현재 plan의 데이터가 있을 경우 복제 여부를 확인
|
||||
|
||||
@ -4,6 +4,7 @@ import fs from 'fs/promises'
|
||||
|
||||
const CAD_FILE_PATH = 'public/cad-images'
|
||||
const IMAGE_FILE_PATH = 'public/plan-bg-images'
|
||||
const FILE_PATH = 'public/plan-images'
|
||||
|
||||
/**
|
||||
* 파일 변환 & 저장
|
||||
@ -39,25 +40,54 @@ const writeImageBase64 = async (title, data) => {
|
||||
return fs.writeFile(`${IMAGE_FILE_PATH}/${title}.png`, data, 'base64')
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미지 저장
|
||||
* Buffer 형식으로 저장
|
||||
* @param {*} title
|
||||
* @param {*} data
|
||||
* @returns
|
||||
*/
|
||||
const writeImageBuffer = async (file) => {
|
||||
// 해당 경로에 Directory 가 없다면 생성
|
||||
// /**
|
||||
// * 이미지 저장
|
||||
// * Buffer 형식으로 저장
|
||||
// * @param {*} title
|
||||
// * @param {*} data
|
||||
// * @returns
|
||||
// */
|
||||
// const writeImageBuffer = async (file) => {
|
||||
// // 해당 경로에 Directory 가 없다면 생성
|
||||
// try {
|
||||
// await fs.readdir(IMAGE_FILE_PATH)
|
||||
// } catch {
|
||||
// await fs.mkdir(IMAGE_FILE_PATH)
|
||||
// }
|
||||
//
|
||||
// const arrayBuffer = await fileURLToPath.arrayBuffer()
|
||||
// const buffer = new Uint8Array(arrayBuffer)
|
||||
//
|
||||
// return fs.writeFile(`${IMAGE_FILE_PATH}/${file.fileName}`, buffer)
|
||||
// }
|
||||
|
||||
const writeImage = async (fileName, file) => {
|
||||
try {
|
||||
await fs.readdir(IMAGE_FILE_PATH)
|
||||
await fs.readdir(FILE_PATH)
|
||||
} catch {
|
||||
await fs.mkdir(IMAGE_FILE_PATH)
|
||||
await fs.mkdir(FILE_PATH)
|
||||
}
|
||||
|
||||
const arrayBuffer = await fileURLToPath.arrayBuffer()
|
||||
const buffer = new Uint8Array(arrayBuffer)
|
||||
|
||||
return fs.writeFile(`${IMAGE_FILE_PATH}/${file.fileName}`, buffer)
|
||||
return fs.writeFile(`${FILE_PATH}/${fileName}.png`, file)
|
||||
}
|
||||
|
||||
export { convertDwgToPng, writeImageBase64, writeImageBuffer }
|
||||
const readImage = async (fileName) => {
|
||||
await fs
|
||||
.readFile(`${FILE_PATH}/${fileName}.png`)
|
||||
.then((res) => {
|
||||
console.log('readImage-then', res)
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log('readImage-catch', e)
|
||||
})
|
||||
}
|
||||
|
||||
const removeImage = async (fileName) => {
|
||||
try {
|
||||
await fs.rm(`${FILE_PATH}/${fileName}.png`)
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
}
|
||||
|
||||
export { convertDwgToPng, writeImageBase64, writeImage, readImage, removeImage }
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user