multer 모듈 설치, multipart/form-data 이용하여 이미지 DB 저장, 이용

tpids·2024년 7월 23일
0

project

목록 보기
8/26

multer 모듈 설치

 npm install multer 

community.js

const upload = require('../middlewares/upload');
const path = require('path');

...

// Create a new post
/**
 * @swagger
 * /community/posts:
 *   post:
 *     summary: Create a new community post
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *               title:
 *                 type: string
 *               content:
 *                 type: string
 *               post_date:
 *                 type: string
 *                 format: date-time
 *               latitude:
 *                 type: number
 *               longitude:
 *                 type: number
 *               image:
 *                 type: string
 *                 format: binary
 *     responses:
 *       201:
 *         description: The created community post
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 post_id:
 *                   type: integer
 *       400:
 *         description: Bad Request - Username does not exist
 *       500:
 *         description: Internal server error
 */
router.post('/posts', upload.single('image'), validatePostInput, async (req, res) => {
    const { username, title, content, post_date, latitude, longitude } = req.body;
    const image = req.file ? req.file.filename : null;
    try {
        const [user] = await db.query('SELECT * FROM User WHERE username = ?', [username]);
        if (user.length === 0) {
            return res.status(400).json({ error: 'Username does not exist' });
        }

        const formattedDate = formatDateToMySQL(post_date);
        const [result] = await db.query(
            'INSERT INTO Community_Post (username, title, content, post_date, latitude, longitude, image) VALUES (?, ?, ?, ?, ?, ?, ?)',
            [username, title, content, formattedDate, latitude, longitude, image]
        );
        res.status(201).json({ post_id: result.insertId, imageUrl: `/uploads/${image}` });
    } catch (err) {
        console.error('Error during POST request:', err);
        res.status(500).json({ error: err.message });
    }
});

...

app.js

const communityRoutes = require('./routes/community'); 
const path = require('path');

...

app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); // 정적 파일 제공을 위한 미들웨어 설정

...

profile
개발자

0개의 댓글