Skip to content

Commit

Permalink
#31 이미지 업로드, 삭제 (s3)
Browse files Browse the repository at this point in the history
s3 이미지 업로드 및 삭제
  • Loading branch information
kth2624 committed May 28, 2022
1 parent 781e9d1 commit a89cfc7
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 14 deletions.
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,3 @@ dist

uploads/
.vscode

awsconfig.json
7 changes: 6 additions & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,10 @@ export const config = {
},
serverUrl: {
serverUrl: required('SERVER_URL','http://localhost:8080/')
},
s3: {
access_key_id: required('ACCESS_KEY_ID'),
secret_access_key: required('SECRET_ACCESS_KEY'),
region: required('REGION'),
}
};
};
31 changes: 24 additions & 7 deletions controller/board.controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as boardRepository from '../data/board.js';

import {s3} from '../s3.js';
//게시글 생성
export async function createPost(req, res) {
const { title, contents, eventId, attendMembers } = req.body;
Expand Down Expand Up @@ -117,25 +117,42 @@ export async function deleteComment(req, res){
await boardRepository.deleteComment(id);
res.sendStatus(204);
}
4

//파일 업로드

export async function upload(req, res, err) {
const boardId = req.body.boardId;
const image = req.files;
console.log(image.length);
console.log(req.fileValidationError);
console.log(`image length = ${image.length}, fileValidationError = ${req.fileValidationError}`);
console.log(image[0]);
const path = image.map(img => img.location);
console.log(`path = ${path}`);
if(req.fileValidationError){//파일이 크거나 형식이 다를때
return res.status(400).send({message: req.fileValidationError});
}
if(image.length < 1){//이미지가 없을때
return res.status(400).send(util.fail(400, "이미지가 없습니다"));
}
const result = await boardRepository.imageUpload(boardId, image )
return res.status(200).send(util.success(200, "업로드를 완료했습니다", path));
const imageId = await boardRepository.imageUpload(boardId, image )
return res.status(200).send(util.success(200, "업로드를 완료했습니다", { imageId: imageId, path: path}));
}

export async function deleteImage(req, res){
const id = req.params.id;
const deleteId = await boardRepository.findByImageId(id);
console.log(deleteId);

if(!deleteId) //삭제할 이미지가 없다면
return res.status(404).json({message: '삭제할 사진이 없습니다'});
s3.deleteObject({
Bucket: 'together42',
Key: deleteId.fileKey
}, function(err, data){
if(err)
console.log(err);
console.log(data);
});
await boardRepository.deleteImage(id);
res.sendStatus(204);
}

const util = {
Expand Down
12 changes: 11 additions & 1 deletion data/board.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export async function imageUpload(boardId, images) {
return db
.query('INSERT INTO image_info (boardNum, filePath, fileName, fileType, fileSize, fileKey) VALUES ?',
[values])
.then((result) => result[0]);
.then((result) => result[0].insertId);
}

export async function getImages(boardId){
Expand All @@ -167,4 +167,14 @@ export async function getImages(boardId){
SELECT id as imageId, boardNum as boardId, filePath FROM image_info WHERE boardNum = ?
`,[boardId])
.then((result)=>result[0]);
}

export async function findByImageId(id) {
return db
.execute('SELECT * FROM image_info WHERE id=?',[id])
.then((result) => result[0][0]);
}

export async function deleteImage(id) {
return db.execute('DELETE FROM image_info WHERE id=?',[id]);
}
9 changes: 6 additions & 3 deletions routes/board.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import express from 'express';
import multer from 'multer';
import multerS3 from 'multer-s3';
import aws from 'aws-sdk';
//import aws from 'aws-sdk';
import path from 'path';
import 'express-async-errors';
import { body } from 'express-validator';
import { validate } from '../middleware/validator.js'
import { isAuth } from '../middleware/auth.js';
import * as boardController from '../controller/board.controller.js';
import { s3 } from '../s3.js';

const __dirname = path.resolve();
const router = express.Router();
aws.config.loadFromPath(__dirname + '/awsconfig.json');
//aws.config.loadFromPath(__dirname + '/awsconfig.json');

const s3 = new aws.S3();
//const s3 = new aws.S3();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads/");
Expand Down Expand Up @@ -93,5 +94,7 @@ router.delete('/comment/:id', isAuth, boardController.deleteComment);
//사진 업로드
router.post('/upload', upload.array("image",8), fileSizeLimitErrorHandler, boardController.upload);

//사진 삭제
router.delete('/image/remove/:id', boardController.deleteImage);

export default router;
8 changes: 8 additions & 0 deletions s3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import aws from 'aws-sdk';
import { config } from './config.js';

export const s3 = new aws.S3({
accessKeyId: config.s3.access_key_id,
secretAccessKey: config.s3.secret_access_key,
region: config.s3.region
})

0 comments on commit a89cfc7

Please sign in to comment.