웹페이지 만들기
일단 파일들을 업로드하기 위한 웹페이지를 띄워야 한다. 이를 위해 express
로 서버를 쓰고, 간단한 index.html
파일을 작성한다.
// app.js
const express = require("express");
const app = express();
const port = 3000;
const path = require("path");
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname, "./index.html"));
});
app.listen(port, () => {
console.log(`App listening at port ${port}`);
});
폼을 이용해 multipart
형식으로 데이터를 POST
하려면 form
태그에 enctype="multipart/form-data"
속성을 반드시 넣어주어야 한다. input
태그의 타입은 file
로 하고, 파일을 여러 개 선택할 수 있게 하려면 multiple="multiple"
속성을 추가하면 된다.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple="multiple">
<ul id="file-list"></ul>
<button>submit</button>
</form>
</body>
<script>
// 업로드한 파일 이름 표시
document.addEventListener("change", (e) => {
const ul = document.getElementById("file-list");
const input = e.target;
let list = "";
[...input.files].forEach((file) => {
list += `<li>${file.name}</li>`;
});
ul.innerHTML = list;
});
</script>
</html>
multer 설정
저장 위치 및 파일 이름 설정
multer.diskStorage()
를 통해 파일들이 저장될 위치와 파일 이름을 지정할 수 있다. 아래의 코드에서 파일들은 루트 디렉토리를 기준으로 tmp/uploads
에 저장되고, 파일 이름은 유저가 업로드한 파일 이름이 그대로 사용된다.
// app.js
const express = require("express");
const app = express();
const port = 3000;
const path = require("path");
// multer 설정 추가
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "tmp/uploads");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname, "./index.html"));
});
app.listen(port, () => {
console.log(`App listening at port ${port}`);
});
multer
공식문서에 따르면 file
객체는 originalname
을 포함해 아래의 속성들을 가진다고 한다.
Key | Description | Note |
fieldname | Fieldname specified in the form | |
originalname | Name of the file on the user's computer | |
encoding | Encoding type of the file | |
mimetype | Mime type of the file | |
size | Size of the file in bytes | |
destination | The folder to which the file has been saved | DiskStorage |
filename | The name of the file within the destination | DiskStorage |
path | The full path to the uploaded file | DiskStorage |
buffer | A buffer of the entire file | MemoryStorage |
미들웨어 설정
POST
요청을 처리하는 라우터에 다음과 같이 multer
를 미들웨어로 지정하면, multer
가 알아서 파일들을 위에서 설정한 경로에 저장해준다. upload.array("files", 10)
에서 "files" 는 input
태그의 name
속성값이고, 10
은 파일의 최대 개수이다. 파일을 여러 개 받아올 때는 upload.array()
를, 하나만 받아올 때는 upload.single()
를 사용한다.
const express = require("express");
const app = express();
const port = 3000;
const path = require("path");
// multer 설정 추가
// 생략...
const upload = multer({ storage: storage });
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname, "./index.html"));
});
// post 요청 처리
app.post("/", upload.array("files", 10), (req, res) => {
console.log(req.files);
res.redirect("/");
});
app.listen(port, () => {
console.log(`App listening at port ${port}`);
});
Reference
'Node.js' 카테고리의 다른 글
Express Project Structure (0) | 2021.09.28 |
---|---|
Express Middleware: The Basics (0) | 2021.09.27 |