프로그래밍/NodeJS

multer로 이미지 업로드하기

타코코딩 2024. 2. 29. 00:05

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 });
});