16강 미니 프로젝트(사진 공유 웹사이트)_2 (AWS)
📌 개념 정리
Express Generator로 생성한 Node.js 프로젝트에 이미지 업로드 기능을 추가하는 실습을 진행합니다. 이미지를 업로드하기 위해 사용되는 주요 패키지는 다음과 같습니다.
- Express: 웹 애플리케이션 프레임워크
- Multer: 이미지 및 파일 업로드 처리용 미들웨어
- Bootstrap: UI 디자인을 위한 오픈소스 CSS 프레임워크
- jQuery: DOM 조작과 Ajax를 쉽게 해주는 자바스크립트 라이브러리
🚦 동작 원리 및 구조
- 클라이언트(브라우저)에서 이미지를 선택하고 서버로 업로드 요청(POST)을 보냅니다.
- 서버에서는 Multer가 이 요청을 처리하여 이미지를 서버 내 특정 폴더에 임시로 저장합니다.
- 최종적으로는 저장된 이미지를 AWS S3와 같은 클라우드 스토리지로 업로드합니다.
💻 express generator 설치
sudo npx express-generator --view=ejs project
💻 express generator 권한바꾸기
sudo chown -R ubuntu:ubuntu project/
💻 코드 예시 및 흐름 분석
✅ 의존성 설치 프로젝트 폴더에서 다음 명령어로 패키지를 설치합니다: cd project
npm install
npm install multer
✅ API 파일 생성 (routes/images.js) 기존의 users.js 파일을 복사하여 새 파일(images.js)을 만듭니다. cd routes
cp users.js images.js
✅ images.js 수정
var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var multer = require('multer');
var upload = multer({ dest: path.join(__dirname, '..', 'uploads') });
router.post('/', upload.single('new-image'), function (req, res, next) {
console.dir(req.file);
res.send();
});
module.exports = router;
✅ 라우터 연결 (app.js) cd project vim app.js
var imagesRouter = require('./routes/images'); // UsersRouter 밑에 9번줄
app.use('/images', imagesRouter); // app.use('/users') 밑에 25번째줄
✅ 뷰 파일 수정 (views/index.ejs) Bootstrap과 jQuery 라이브러리를 연결하고 파일 업로드 인터페이스를 추가합니다. cd views vim index.ejs
- 헤드 태그 내부:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> // link rel 밑에 6번째줄
- 바디 태그 하단:
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.5/dist/js/bootstrap.bundle.min.js" integrity="sha384-k6d4wzSIapyDyv1kpU366/PK5hCdSbCRGRCMv+eplOQJWyd1fbcAu9OCUj5zNLiq" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.5/dist/js/bootstrap.min.js" integrity="sha384-VQqxDN0EQCkWoxt/0vsQvZswzTHUVOImccYmSyhJTp7kGtPed0Qcx8rK9h9YEgx+" crossorigin="anonymous"></script>
// body 부분 <p> welcome 부분에 insert
- 파일 업로드 폼 추가: bootstrap input 파일에서 custom file 클릭한후 코드복
<div class="input-group mb-3">
<label class="input-group-text" for="file-upload">Upload</label>
<input type="file" class="form-control" id="file-upload" name="new-image">
</div>
// body <p> welcome to 밑에 위치
// label class for="inputGroupfile01" 에서 for="file-upload" 로 변경
// input type id="inputGroupfile01" 에서 id="file-upload" 로 변경
// id="file-upload" 옆에추가 name="new-image">
<div id="progres" class="progress" role="progressbar" aria-label="Animated striped example" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
</div>
// progress bar 설치 Animated stripes
// div id="progress" 추가 aria-valuenow="0"으로 변경 style="width:0% 변경
✅ Query UI 라이브러리 (하단 스크립트) jQuery애서 jQuery 3.x minified 코드 프로그레스바 밑에 붙여넣기
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
✅ Query UI 라이브러리 (하단 스크립트) jQuery UI 1.14애서 minified 코드 프로그레스바 밑에 붙여넣기
<script src="https://code.jquery.com/ui/1.14.1/jquery-ui.min.js" integrity="sha256-AlTido85uXPlSyyaZNsjJXeCs07eSv3r43kyCVc8ChI=" crossorigin="anonymous"></script>
✅ blueimp 이미지 업로드, 갤러리, 파일 업로드 등 UI 관련 jQuery 기반 라이브러리
<script src="https://blueimp.github.io/jQuery-File-Upload/js/jquery.fileupload.js"
crossorigin="anonymous"></script>
✅ 파일 업로드 처리 코드 (하단 스크립트)
<script>
$(function () {
$('#file-upload').fileupload({
url: '/images',
dataType: 'json',
progressall: function (e, data) {
var progress = parseInt(
(data.loaded / data.total) * 100,
10
);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
},
});
});
✅ 파일 업로드 처리 코드 (하단 스크립트) 하단부는 확인필요
$('#fileUpload').on('change', function(){
var formData = new FormData();
formData.append('newImage', $('#fileUpload')[0].files[0]);
$.ajax({
url: '/images',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
$('#progress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(data){
alert(data);
}
});
});
🧪 실전 사례
- 위 작업 후, 서버를 실행하여 브라우저에서 파일 업로드를 진행합니다:
npm start
- EC2 퍼블릭 IP 뒤에 포트 3000을 붙여 접속해 이미지를 업로드하면 서버의 'uploads' 폴더에 이미지가 저장됩니다.
🧠 고급 팁 or 자주 하는 실수
- 📍 SSH로 EC2 접속 확인: 로컬 터미널에서 명령을 실행하지 않고 EC2 인스턴스에 SSH로 접속 후 작업합니다.
- 📍 파일 경로 주의: 코드 수정 시 경로가 맞는지 정확히 확인해야 합니다. 특히 views 폴더나 routes 폴더의 경로를 잘 확인하세요.
- 📍 라이브러리 URL 정확히 복사: Bootstrap과 jQuery CDN URL을 정확히 붙여 넣어야 합니다.
✅ 마무리 요약 및 복습 포인트
✔️ Express Generator로 빠르게 프로젝트 초기 설정을 합니다. ✔️ Multer를 이용해 간단히 파일 업로드 기능을 구현합니다. ✔️ Bootstrap 및 jQuery를 통해 UI와 인터랙션을 구현합니다. ✔️ 파일 업로드 시 Ajax를 사용해 서버와 비동기 통신을 합니다.
이 과정을 통해 이미지 업로드의 전체적인 흐름과 API 통합 방법을 익힐 수 있습니다.