• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

multer 이미지 업로드 오류 질문드립니다

22.11.17 22:25 작성 조회수 388

0

드롭존을 사용하여 이미지 업로드를 했을때,

서버 단에서

TypeError: Cannot read properties of undefined (reading 'path')

라는 에러 메시지와 함께 업로드가 완료되지 않는 문제가 발생했습니다.

클라이언트 단에서는

POST http://localhost:3000/api/products/image 500 (Internal Server Error)

라는 500 서버 에러가 발생했다고 나왔었구요

 

한가지 의문인 것은,

여러 방법을 시도해보다가

FileUpload 유틸에서 axios headers config를 삭제하고 시도하니 제대로 잘 동작을 하였습니다..

 

유추해보건데, 다른 코드들은 잘 작성되어 동작하지만 해당 config 부분에서 문제가 생긴 것 같습니다, 그렇다면 이유가 무엇인지 궁금합니다

 

  1. FileUpload.js

import React from "react";
import Dropzone from "react-dropzone";
import axios from "axios";

const FileUpload = () => {
  const dropHandler = (files) => {
    // console.log("dropped file", files); // 파일은 잘 들어옴

    console.log(files);

    let formData = new FormData();

    // const config = {
    //   headers: { "content-type": "multipart/form-data" },
    // };

    formData.append("file", files[0]);

    // axios.post("/api/products/image", formData, config).then((res) => {
    axios.post("/api/products/image", formData).then((res) => {
      if (res.data.success) {
        console.log(res.data);
      } else {
        alert("파일을 저장하는데 실패하였습니다");
      }
    });
  };

  return (
    <Dropzone onDrop={dropHandler}>
      {({ getRootProps, getInputProps }) => (
        <section>
          <div
            style={{
              width: "400px",
              height: "400px",
              backgroundColor: "white",
              border: "1px solid lightgray",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
            {...getRootProps()}
          >
            <input {...getInputProps()} />
            <p style={{ fontSize: "5rem" }}>+</p>
          </div>
        </section>
      )}
    </Dropzone>
  );
};

export default FileUpload;

 

  1. products.js (강의와 다르게 product"s"로 바꾸고 관련 코드들도 수정하였었습니다)

const express = require("express");
const router = express.Router();
const multer = require("multer");

//=================================
//             Product
//=================================

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  }, // 파일이 어디에 저장이 되는가에 대한 부분

  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage: storage }).single("file");

router.post("/image", (req, res) => {

  console.log(storage.filename);

  upload(req, res, (err) => {
    if (err) {
      return res.json({ success: false, err });
    }
    return res.json({
      success: true,
      filePath: res.req.file.path,
      fileName: res.req.file.filename,
    });
  });
});

module.exports = router;

답변 0

답변을 작성해보세요.

답변을 기다리고 있는 질문이에요.
첫번째 답변을 남겨보세요!