E-book (9) 내용등록

이율곡·2023년 1월 28일
0

Project

목록 보기
11/15
post-thumbnail

서두

책을 대여하면 그 책의 내용을 볼 수 있게 내용 등록을 설정했다. 가장 좋은 것은 리딩(reading) 프로그램을 만드는 것이지만 프로그램은 쉽지 않아서 pdf를 읽으려 한다.


Table

CREATE TABLE book_content (
	content_number INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
	content_name VARCHAR(200) NOT NULL,
	content_path VARCHAR(200) NOT NULL,
	created_at TIMESTAMP DEFAULT NOW(),
	updated_at TIMESTAMP DEFAULT NOW(),
	admin_number INT NOT NULL,
	FOREIGN KEY (admin_number) REFERENCES admin (admin_number)
);

내용 테이블이다. image 테이블처럼 이름과 경로만 설정했다.

Routes

이번에 내용 등록을 하기 위해서 코드를 변경했다.

const multer = require("multer");

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    let fileDest;
    if (file.mimetype === "application/pdf") {
      fileDest = "static/contents";
    } else {
      fileDest = "static/images";
    }
    cb(null, fileDest);
  },
  filename: (req, file, cb) => {
    cb(null, file.filename + "-" + file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg" ||
    file.mimetype === "application/pdf"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

우선 app.js에 있는 multer 모듈과 관련된 코드를 adminRoutes파일로 옮겼다. 그리고 image와 pdf 파일에 따른 저장경로를 다르게 설정했다. fileFilter에도 pdf파일을 추가했다. pdf파일은 mimetype을 application으로 설정해주어야 한다.

routes.post('/imageRegistAction', multer({ storage: fileStorage, fileFilter: fileFilter }).single("image"), imageController.imageRegistAction);
routes.post('/contentRegistAction', multer({ storage: fileStorage, fileFilter: fileFilter }).single("content"),contentController.contentRegistAction);

그리고 Controller에 multer를 위와 같이 지정해주어야 한다. image와 pdf에 따라 single이 다르기 때문이다.(single 안에 있는 string은 ejs에서 설정한 file의 name이다)

Controller

admin폴더에 content.js파일을 만들어주었다.

const Content = require("../../models/admin/content");

exports.getContentRegist = (req, res, next) => {
  res.render("admin/regist/content", {
    pageTitle: "E-Book Content Regist",
    member: req.session.user,
    admin: req.session.admin,
  });
};

exports.contentRegistAction = (req, res, next) => {
  let content = req.file;
  let adminNumber = req.session.admin.admin_number;

  Content.contentRegistAction(content, adminNumber, (err) => {
    if (err) {
      console.log("내용 등록 에러 : " + err);
    } else {
      console.log("내용 등록 성공!!");
      res.render("admin/adminIndex", {
        pageTitle: "Welcome E-book Admin Page",
        member: req.session.user,
        admin: req.session.admin,
      });
    }
  });
};

getContentRegist는 내용 등록하는 페이지로 이동하는 컨트롤러이고 contentRegustAction은 파일을 DB에 저장하는 모델과 연결한 컨트롤러다.

Model

컨트롤러처럼 admin폴더에 content 파일을 만들었다.

module.exports = class Content {
  constructor(contentName, contentPath) {
    this.contentName = contentName;
    this.contentPath = contentPath;
  }

  static contentRegistAction(content, adminNumber, cb) {
    if (content) {
      let contentName = content.originalname;
      let contentPath = content.path;

      let sql =
        "INSERT INTO book_content (content_name, content_path, admin_number) VALUES (?, ?, ?)";
      let param = [contentName, contentPath, adminNumber];

      connection.query(sql, param, (err, row, fields) => {
        if (err) {
          console.log("내용 등록 쿼리 오류 : " + err);
        } else {
          console.log("내용등록 성공");
          cb();
        }
      });
    } else {
      console.log("내용이 등록되지 않았습니다.");
    }
  }
};

image등록과 똑같이 내용들을 설정해주었다.

View

View 또한 image를 등록할 때와 똑같다. admin/regist에 contetn.ejs 파일을 만들었다.

<%- include('../../admin/includes/admin-head-nav.ejs')%>
    <div class="container px-4 px-lg-5">
        <div class="row gx-4 gx-lg-5 align-items-center my-5 ">
            <form action="/contentRegistAction" method="POST" enctype="multipart/form-data">
                <label for="content">책 내용</label>
                <input type="file" name="content" id="content">
                <button type="submit" class="btn btn-primary">등록하기</button>
            </form>
        </div>
    </div>
<%- include('../../admin/includes/admin-footer.ejs')%>        

여기서 설정한 file의 name이 multer.single 함수와 연결이 된다.


최종적으로 등록되는 파일과 이미지

정리하기

이번 내용 등록까지 하면서 본격적인 도서등록 전에 해야할 것들을 마쳤다. 도서분류, 작가, 이미지, 내용들을 어떻게 하는지 배우고 이해했다. 가장 중요한 도서만 등록하면 나머지는 관리(수정, 삭제)로 새로운 부분으로 넘어간다.

등록 부분도 다양하게 하면서 많은 도움이 되었고 Velog에 정리를 하면서 하니 더욱 공부가 되는 것 같다. 기능이 어느 정도 마무리 되면 css를 정리하고 깔끔한 예시들 캡쳐로 남기고 싶다.

profile
음악을 좋아하는 사람이 음악을 만들 듯, 개발을 좋아하게 될 사람이 쓰는 개발이야기

0개의 댓글