Page tree
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

server.js
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const router = express.Router();

router.post('/request', (req, res) => {
	const file = _.get(req, ['file']);
	const filePath = _.get(file, 'path');
	const page = _.get(req.body, ['page']) || 0;
	const originalName = _.get(file, 'originalname');
	const mimeType = _.get(file, 'mimetype');
	const extension = path.extname(originalName).split('.')[1] || mimeType.split('/')[1];
	const filePathWithExt = filePath + '.' + extension;

	fs.renameSync(filePath, filePathWithExt);
	try {
		const ocrResult = await requestOCR(filePathWithExt, page);
		const imagePath = await downloadImage(ocrResult.result.masked_image);
		res.end(JSON.stringify({ result: ocrResult.result, imagePath }));
	} catch (error) {
		res.status(error.status).send(error.message);
	}
}

function requestOCR('/request', (imgPath, page) => {
    const apiKey = OCR_API_KEY; // 발급 받은 OCR API Key를 입력합니다.
    const options =  {
		url: `${OCR_SDK_URL}/ocr`,
		formData: {
			api_key: OCR_API_KEY,
			image: fs.createReadStream(imgPath),
			page_index: page,
			...OCROption
		}
    };
	
	request.post(options).on('response', response => {
        const statusCode = _.get(response, 'statusCode');
        const statusMessage = _.get(response, 'statusMessage');
        if (statusCode === 200) {
            console.log('OCR 성공');
            let body = [];
            response.on('error', (err) => {
                throw err;
            }).on('data', (chunk) => {
                body.push(chunk);
            }).on('end', () => {
                // 전송 완료
                const data = JSON.parse(Buffer.concat(body).toString());
                // 클라이언트에게 응답
                return res.status(statusCode).json(data);
            });
        } else {
            console.log('OCR 실패', statusCode);
            const error = new Error(statusMessage);
            error.status = statusCode;
            // 클라이언트에게 오류 응답
            return res.status(statusCode).json({ error: statusMessage });
        }
    });
}

function downloadImage(fileName) {
    return new Promise((resolve, reject) => {
        const options = {
            url: `${OCR_SDK_URL}/out/${fileName}`,
            formData: {
                api_key: OCR_API_KEY,
            }
        };

        const imagePath = path.resolve(WORK_DIR, fileName);
        request.post(options).on('response', response => {
            const statusCode = _.get(response, 'statusCode');
            const statusMessage = _.get(response, 'statusMessage');
            if (statusCode === 200) {
                console.log('OCR image download 성공');

                let imageData = Buffer.from([]);
                response.on('data', (chunk) => {
                    imageData = Buffer.concat([imageData, chunk]);
                }).on('end', () => {
                    const relativeImagePath = '/' + path.relative(ROOT_DIR, imagePath).replace(/\\/g, '/');
                    fs.writeFileSync(imagePath, imageData); // 이미지 저장
                    resolve(relativeImagePath);
                });
            } else {
                console.log('OCR image download 실패', statusCode);
                const error = new Error(statusMessage);
                error.status = statusCode;
                reject(error);
            }
        });
    });
}

app.use(bodyParser.json());
app.use('/', router);
app.listen(8080);
  • No labels