티스토리 뷰

JavaScript/JS백엔드

[Express] 파일 업로드

염두리안 2025. 1. 14. 00:56
728x90
반응형

파일과 multipart/form-data

 

MIME 타입 (IANA 미디어 타입) - HTTP | MDN

미디어 타입 (Multipurpose Internet Mail Extensions 또는 MIME type로도 알려져 있음)이란 문서, 파일 또는 바이트 집합의 성격과 형식을 나타냅니다. MIME 타입은 IETF의 RFC 6838에 정의 및 표준화되어 있습니다

developer.mozilla.org

 

multer 미들웨어 사용하기

npm install multer
import multer from 'multer';

const upload = multer({ dest: 'uploads/'});

// 하나의 파일을 attachment로 받음
app.post('/files', upload.single('attachment'), (req, res) => {
  console.log(req.file);
  res.json({ message: '파일 업로드 완료!' });
});

 

서버의 파일 제공하기

// app.js
// uploads 폴더에 저장된 각각의 파일에 접근 가능
app.use(express.static('uploads'));

// 파일 경로 추가 가능
app.use('/files', express.static('uploads'));
// 접근시 http://localhost:3000/files/파일명 으로 접근

// 파일에 접근 가능한 경로를 리스폰스로 받기
app.post('/files', upload.single('attachment'), (req, res) => {
  const path = `/files/${req.file.filename}`;
  console.log(req.file);
  res.json({ path });
});

POST GET

 

multer 라이브러리에서 multer 인스턴스 생성

>> npm install --save multer-s3

const upload = multer({ storage: ... })

 

728x90
반응형

'JavaScript > JS백엔드' 카테고리의 다른 글

[JS백엔드] 위임  (0) 2025.01.14
[JS백엔드] 인증과 인과  (0) 2025.01.14
[Express] 라우터  (1) 2025.01.14
[Express] 미들웨어  (1) 2025.01.13
물리적 모델링  (0) 2025.01.02
최근에 올라온 글
최근에 달린 댓글
«   2025/06   »
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
Total
Today
Yesterday
반응형