inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

비전공자를 위한 진짜 입문 올인원 개발 부트캠프

multer시 file.path 관련

해결된 질문

773

이유진

작성한 질문수 7

1

multer를 이용한 uploads 폴더에 이미지 업로드시 

file 로그를 찍어보면 아래와 같이 path에서 \\ 두번 찍힙니다

postman으로 확인해도 마찬가지고요

filename과 destination은 정상인데 어디서 두번 찍히게 되는지 모르겠네요.

아래는 로그로 찍어본 file과 server.js 전체 코드입니다

근데 또 file.path로 찍어보면 uploads\join.jpg 로 찍혀서 해당 폴더에 이미지는 올라가고 있어요

{

  fieldname: 'image',

  originalname: 'join.jpg',

  encoding: '7bit',

  mimetype: 'image/jpeg',

  destination: 'uploads/',

  filename: 'join.jpg',

  path: 'uploads\\join.jpg',

  size: 88818

}

 

const express = require("express");
const cors = require("cors");
const app = express();
const port = 8080;
const models = require("./models");
const multer = require("multer");
const upload = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, "uploads/");
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname);
    },
  }),
});
app.use(express.json());
app.use(cors());
app.use("/uploads", express.static("uploads"));

app.get("/products", (req, res) => {
  models.Product.findAll({
    //limit : 1,
    order: [["createdAt", "DESC"]],
    attributes: ["id", "name", "price", "createdAt", "seller", "imageUrl"],
  })
    .then((result) => {
      console.log("products : ", result);
      res.send({
        products: result,
      });
    })
    .catch((error) => {
      console.log("error : ", error);
      res.send("에러발생");
    });
});

app.post("/image", upload.single("image"), (req, res) => {
  const file = req.file; //저장된 이미지 정보 get
  console.log("file : ", file);
  console.log("file path====", file.path);
  res.send({
    imageUrl: file.path,
  });
});

app.post("/products", (req, res) => {
  const body = req.body;
  const { name, description, price, seller } = body;
  if (!name || !description || !price || !seller) {
    res.send("모든 필드를 입력해주세요.");
  }
  models.Product.create({
    name,
    description,
    price,
    seller,
  })
    .then((result) => {
      console.log("상품 생성 결과 : ", result);
      res.send({
        result,
      });
    })
    .catch((error) => {
      console.error(error);
      res.send("상품 업로드에 문제가 발생");
    });
  res.send({
    body,
  });
});

app.get("/products/:id", (req, res) => {
  const params = req.params;
  const { id } = params;
  models.Product.findOne({
    where: {
      id: id,
    },
  })
    .then((result) => {
      console.log("product : ", result);
      res.send({
        product: result,
      });
    })
    .catch((error) => {
      console.log(error);
      res.send("상품 조회에 에러가 발생했습니다.");
    });
});

app.listen(port, () => {
  console.log("그랩에 쇼핑몰 서버가 돌아가고 있습니다.");
  models.sequelize
    .sync()
    .then(() => {
      console.log("db 연결 성공");
    })
    .catch((err) => {
      console.log(err);
      console.log("db 연결 에러");
      process.exit();
    });
});

react tensorflow nodejs express 머신러닝 배워볼래요? react-native javascript HTML/CSS

답변 1

1

그랩

multer 상에서 결과를 표현할 때 저렇게 보여주는 것 같습니다!

실제로 윈도우에서는 경로를 표현할 때 backslash(\) 나 double backslash(\\) 모두 동일한 결과를 내므로 걱정할 필요는 없을 것 같습니다 :)

https://stackoverflow.com/questions/15969608/what-is-the-difference-between-and-in-file-path

0

이유진

감사합니다^^!

[해결]그랩님 답변 주세요.

0

190

2

그랩님의 답변을 기다립니다/102강 전반적인 에러

0

162

2

[그랩님께]101강 안드로이드 에러들(Key prop)해결방법 궁금합니다.

0

139

2

[재질문][그랩님 답변 부탁드립니다]101강

0

162

2

[그랩님 답변 부탁드립니다]101강 Axios 에러와 502 Bad Gateway 질문

0

118

2

Ngrok 설치 후 forwarding Url 에러

0

144

2

[그랩님께,Ngrok 악성코드 인식 해결방법]질문 드립니다.

0

250

2

Ngrok 설치 후 forwarding Url로 연결 불가

0

156

1

그랩님,[꼭] 답변 부탁드립니다.

0

76

1

[꼭][[꼭] 그랩님, 답변 부탁드립니다], Failed to load resource: the server responded with a status of 404 (Not Found) 상품 상세 페이지 질문입니다.

0

162

1

6강/7강 수업

0

56

1

그랩님, 상품 상세 페이지 에러와 의문점 질문드립니다.

0

105

2

그랩님, 해결되지 않은 에러 메시지 [꼭] 답변 부탁 드립니다.

0

148

2

[재 질문]Cannot read properties of undefined (reading 'map') TypeError: Cannot read properties of undefined (reading 'map') 에러 해결 어떻게 하나요?

0

94

1

Cannot read properties of undefined (reading 'map') TypeError: Cannot read properties of undefined (reading 'map') 에러 해결 어떻게 하나요?

0

134

2

일반적인 css 꾸미기에서 width와 height의 값?

0

98

2

Windows에서의 업로드 후 홈화면 상품이미지 오류 해결방법

0

204

1

그랩마켓 웹화면 구현하기 -2 질문입니다.

0

127

1

react에 반영이 되지 않습니다.

0

249

1

터미널 npm install -g create-react-app 작성 후 오류

0

430

1

create-react-app my app 실행 시 에러

0

358

2

포스트맨 질문

0

105

1

<꼭 답변 부탁 드립니다>그랩선생님, [컴포넌트 사용하기] 강의에서 질문 있습니다.

0

269

2

그랩선생님, 질문 답변 부탁 드립니다.vscode에서 npm install -g create-react-app 입력 후 에러 입니다.

0

491

2