Node.js - multer , dotenv

ryan·2022년 5월 16일
0

인프런 Node.js 교과서

multer

  • form의 enctype이 multipart/form-data인 경우 body-parser로 폼 요청 본문을 해석할 수 없음
    • enctype form method가 post인 경우에만 사용할 수 있으며 폼 데이터가 서버로 제출될 때 인코딩 되는 방법을 명시
  • multer 함수를 호출하여 multipart/form-data를 읽을 수 있다
html
<form id="form" action="/upload" method="post" enctype="multipart/form-data">
  //  upload.single사용할 때 
  // multiple attribute속성을 이용하여 이미지 여러개를 하나로 묶어서 보낼 수 있다. 대신 upload.array('image')로 받야아 함
   
  <input type="file" name="image" multiple/> 
----
  //파일이 여러개인 경우 upload.fields([{name:'image1},{name:image2}) 와 같으 식으로 객체로 넣어줘야 함.
  <input type="file" name="image1" />
  <input type="file" name="image2" />
  <input type="text" name="title" />
  <button type="submit">업로드</button>
</form>
<script>
	...
  const formData = new FormData();
  formData.append('image', e.target.image.files[0]) // 이미지 데이터 전달 req.file로 받음
  formData.append('title', e.target.title.value) // 타이틀 전달 req.body.title로 받아야함.
  axios.post('/upload',formData);
</script>
js file
const multer = require('multer')

try{
fs.readdirSync('uploads')
} catch (error){
console.error('uploads 폴더 없으면 uploads 폴더 생성')
  fs.mkdirSync('uploads')


const upload = multer({ // 멀터 호출
  storage:multer.diskStorage({  // 업로드한 파일을 어디에 저장할 것인가. // multer google cloud storage등의 서비스를 이용하기도 함.
    destination(req,file,don){ // destination어디에 저장할지
      done(null,'uploads/'); // 'upload' 폴더에 저장하겠다는 뜻 
    },
    filename(req,file,done){
      const ext = path.extname(file.originalname); // 확장자 추출
      done(null,path.basename(file.originalname,ext) + Date.now() + ext); // 파일이름 날짜 확장자 (날짜를 붙힌 이유는 파일명이 같아서 덮어씌워지는걸 방지하기 위해)
    },
  }),
  limis:{fileSize : 5 * 1024 * 1024}, // 파일 사이즈( 5 * kb * mb) 
});
  
app.post('/upload',upload.single('image'),(req,res)=>{ //upload.single > 한개의 파일만 업로드 할 때
console.log(req.file); 업로드된 정보는 req.file에 저장됨
  res.send('ok')
});
                              
  • storage : 저장할 공간에 대한 정보
  • diskStorage : 하드디스크에 업로드 파일을 저장
  • destination : 저장할 경로
  • filename : 저장할 파일명
  • Limits 파일 개수나 파일 사이즈 제한

dotenv

  • 환경 변수와 같이 시스템에 따른 설정을 관리함. (cookieParser 암호화 key 등)
  • dotenv 패키지 install
  • 프로젝트 파일 내에 .env 파일 생성
.env file
COOKIE_SECRET=1234646
DB_PASSWORD=sdsadsdww
server.js
const dotenv = require('dotenv')
dotenv.config(); // process.env를 사용하는 패키지보다 상단에 써줘야 한다. 

app.use(cookieParser(process.env.COOKIE_SECRET))   
  • .env 파일은 드라이브나 클라우드에 올리면 안된다.
profile
프론트엔드 개발자

0개의 댓글