multer 라이브러리 써서 이미지 업로드하기
- 기존에는 presigned url 방식으로 aws s3 나 cloudflare 저장소에 업로드했는데 서버단에 이미지를 저장하는 방법으로 multer라이브러리 사용을 해보겠음
- 프론트단
const avatarChange = watch("user_avatar");
useEffect(() => {
if (avatarChange && avatarChange.length > 0) {
const file = avatarChange[0];
setAvatarPreview(URL.createObjectURL(file));
}
}, [avatarChange]);
// submit 함수 안
if (avatarChange && avatarChange.length > 0) {
const file = avatarChange[0];
const form = new FormData();
form.append("file", file);
const response = await axios.post(
`http://localhost:8081/user/uploads?id=${user?.id}`,
form
);
querystring 으로 파일이름을 유저아이디로 하기위해서 ?id=를 추가했음.
같은 이름으로 보내면 덮어쓰기가 자동으로 됨
- 서버단
npm i multer //설치
const upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/"); //폴더경로 서버단에 uploads라는 폴더를 만들었음
},
filename: function (req, file, cb) {
const { id } = req.query;
cb(null, id + "." + file.originalname.split(".")[1]); querystring으로보낸자료에 확장자붙임
},
}),
});
router.post("/uploads", upload.single("file"), (req, res) => {
console.log(req.file);
res.json({ ok: true });
});
'프로그래밍 > NodeJS' 카테고리의 다른 글
nestjs docker 도커 및 typeorm 세팅 enum 프로퍼티 (0) | 2024.03.17 |
---|---|
nestjs 프로젝트생성 및 기본사용법 (4) | 2024.03.12 |
2023.11.29+ node js 게시판 연습 (my sql,react) 게시글 post (0) | 2023.11.29 |
이미지 업로드 (0) | 2023.11.27 |
NodeJS React환경에서 로그인 기능(쿠키) 구현하기 (3) | 2023.11.17 |