강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

kks01301님의 프로필 이미지
kks01301

작성한 질문수

nextjs react-quill 이미지 저장 질문이용

작성

·

526

0

nextjs에서 react-quill에서 이미지 업로드 시 nestjs에서 multer로 이미지 받아서 저장하려고 하는데 개발 초보라 아무리 구글링해도 왜 안되는지 모르겠네요 ㅜㅜ

 

포스트맨에서 nest.js upload api 보내면 정상적으로 파일 저장 되는데 next.js에서 upload 요청 보내면 nest.js에서 file이 undefined 출력됩니다.

 

QuillEditor.tsx에서 const file = input.files[0] 콘솔로 찍어보면 아래 이미지처럼 표시되는데 이거 formdata 제대로 생성된게 맞나요?

 

구글링하면서 몇시간 테스트해도 안되네요. 포스트맨에서 요청하면 정상적으로 되는거 보면 next.js 쪽 문제 맞는거 같은데 아무리 구글링해봐도 이유를 모르겠네요..

 

QuillEditor.tsx

"use client";
import ReactQuill from "react-quill";
import { useMemo, useRef, useState } from "react";
import "react-quill/dist/quill.snow.css";
import imgUpload from "./imgUpload";

export default function QuillEditor() {
  const [content, setContent] = useState("");
  const quillRef = useRef(null);

  const imageHandler = () => {
    const input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.click();

    input.onchange = async () => {
      const file = input.files[0];

      // 현재 커서 위치 저장
      // const range = getEditor().getSelection(true);
      // const range = quillRef.selection;

      // 서버에 올려질때까지 표시할 로딩 placeholder 삽입
      // quillRef.getEditor().insertEmbed(range.index, "image", `'로딩중'`);

      const formData = new FormData();
      formData.append("file", file);
      try {
        // console.log(formData.get("file"));

        // console.log(url);
        // quillRef.getEditor().deleteText(range.index, 1);
        // quillRef.getEditor().insertEmbed(range.index, "image", url);
        // quillRef.getEditor().setSelection(range.index + 1);
        const result = await imgUpload(formData);

        // console.log(result);
      } catch (error) {
        console.log(error);
      }
    };
  };

  const modules = useMemo(() => {
    return {
      toolbar: {
        container: [
          [{ size: ["small", false, "large", "huge"] }],
          [{ header: "1" }, { header: "2" }, { font: [] }],
          [{ align: [] }],
          ["bold", "italic", "underline", "strike"],
          [
            { list: "ordered" },
            { list: "bullet" },
            { indent: "-1" },
            { indent: "+1" },
          ],
          [
            {
              color: [],
            },
            { background: [] },
          ],
          ["link", "image", "video"],
        ],
        handlers: { image: imageHandler },
        clipboard: {
          matchVisual: false,
        },
      },
    };
  }, []);

  const formats = [
    "font",
    "header",
    "bold",
    "italic",
    "underline",
    "strike",
    "blockquote",
    "list",
    "bullet",
    "indent",
    "link",
    "align",
    "color",
    "background",
    "size",
    "h1",
    "image",
    "video",
  ];

  return (
    <>
      <div>
        <ReactQuill
          ref={quillRef}
          style={{ width: "800px", height: "600px" }}
          modules={modules}
          formats={formats}
          onChange={(e) => {
            setContent(e);
            console.log(e);
          }}
          // onChange={setContent}
          theme="snow"
        />
      </div>
    </>
  );
}

 

imgUpload.ts

import axios from "axios";

export default async function imgUpload(file: any) {
  console.log(file.get("file"));

  const result = await axios
    .post(
      `${process.env.NEXT_PUBLIC_API_SERVER}/files/upload`,
      {
        file,
      },
      {
        headers: {
          // Accept: "image/*",
          "Content-Type": "multipart/form-data",
        },
      }
    )
    .then((res) => {
      return res.data;
    });

  console.log(result.data);

  return result;
}

 

nest.js

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
  ) {
    console.log(file);
    // return await this.filesService.fileUpload(files);
  }

답변 1

0

안녕하세요, 인프런 AI 인턴입니다.

kks01301님, 질문하신 내용을 기반으로 한 번 살펴보겠습니다. Next.js에서 React-Quill을 사용하여 이미지 업로드를 Nest.js에 구현하려 할 때 발생하는 문제로 보입니다. 주요 이슈는 Nest.js에서 파일이 undefined로 출력된다는 점입니다.

분석해 본 결과, imgUpload.ts 파일의 문제인 것 같습니다. Axios 요청을 보낼 때 파일 데이터를 제대로 전송하지 않아 발생하는 문제로 추정됩니다. 여기서 중요한 포인트는, axios.post의 두 번째 인자로 파일을 담고 있는 FormData 객체를 전달할 때는, 객체를 그대로 전달해야 합니다. 현재 코드에서는 파일을 {file} 형태로 전달하고 있는데, 이렇게 전달하면 서버 측에서는 제대로 된 FormData 형태로 인식하지 못하고, 결과적으로 파일이 undefined로 처리됩니다.

따라서, imgUpload.tsaxios.post 부분을 아래와 같이 수정해야 합니다.

const result = await axios.post(
  `${process.env.NEXT_PUBLIC_API_SERVER}/files/upload`,
  file, // 여기서 file은 FormData 객체입니다.
  {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }
).then((res) => {
  return res.data;
});

이와 같이 수정하면, FormData에 담긴 파일이 제대로 서버로 전송되어 Nest.js에서도 파일을 올바르게 처리할 수 있을 것입니다.

질문하신 내용에 대한 도움이 되었기를 바랍니다. 추가적인 궁금증이나 질문이 있으시면 언제든 질문해 주세요.

kks01301님의 프로필 이미지
kks01301

작성한 질문수

질문하기