Nodejs express로 에어비앤비 클론코딩 해보기 3.

숙소 업로드 구현

숙소 업로드 라우터

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
try {
fs.readdirSync('uploads');
} catch (error) {
console.error('uploads 폴더가 없어 uploads 폴더를 생성 합니다.');
fs.mkdirSync('uploads');
}

const upload = multer({
storage: multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
const ext = path.extname(file.originalname);
cb(null, path.basename(file.originalname, ext) + Date.now() + ext);
},
}),
});

// 게시글 업로드
router.post('/host', isLoggedIn, upload.array('img'), async (req, res, next) => {
const hostaddress = req.body.firstCity.concat(" ", req.body.middleCity," ", req.body.hostaddress);

try{
const newHost = await Host.create({
title: req.body.title,
hostaddress,
city: req.body.firstCity,
person: req.body.person,
roominfo_room: req.body.room,
roominfo_bed: req.body.bed,
roominfo_cook: req.body.cook,
roominfo_bathroom: req.body.bathroom,
hostinfo: req.body.hostinfo,
hosttype: req.body.hosttype,
UserId: req.user.id,
});
for(i=0; i<req.files.length; i++){
let newImage = await Image.create({
src: "img/" + req.files[i].filename,
HostId: newHost.id,
});

}
console.log("success");
res.redirect('/');
} catch (error) {
console.log(error);
next(error);
}
});

숙소 업로드 라우터는 숙소 정보를 담는 Host모델과 숙소의 사진을 담는 Image모델을 사용하여 업로드를 진행한다.

사진 파일들은 multer 모델을 사용하여 업로드했고 이미지의 파일 이름을 Image모델에 담아 주었다.

이미지 업로드는 이미지의 갯수 만큼 생성하도록 반복문을 사용하여 진행했는데 더 좋은 방법이 있을 수 도 있지만 간단하게 구현 했다.

결과

숙소 정보를 입력해주고 데이터를 서버로 보낸다.

입력한 데이터가 hosts 테이블에 잘 저장 되었다.

이제 입력한 데이터들을 화면에 뿌려 주면 된다.

보완점

업로드 라우터에서 업로드를 실행 하기 전에 로그인 여부를 확인하는 미들웨어를 사용했는데 이 미들웨어는 로그인 여부만 확인 해줄 뿐 사용자가 호스트 권한이 있는지 여부는 확인 해 주지 않는다.

호스트를 확인 할 수 있는 미들웨러를 따로 만들면 라우터 코드가 줄고 간결할 것 같다.

Author

han Ju Ryeon

Posted on

2021-09-09

Updated on

2021-12-05

Licensed under

댓글