React CKEditor 이미지 업로드 시 새로고침 문제

React CKEditor 이미지 업로드 시 새로고침 문제

작성일 2023.08.11댓글 1건
    게시물 수정 , 삭제는 로그인 필요

아래의 코드는 공식 가이드와 블로그를 참고해서 작성한 로직인데 이미지를 업로드 하면 10번중에 9번은 페이지가 새로고침 됩니다.. 어디서 생기는 오류일까요??

업로드 하는 파일의 이름은 한국어+영어+숫자+특수문자 등이 섞여있습니다

import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

const TextEditorInCommunity = ({ textData, textDataFun, img, setImgList }) => {
  const customUploadAdapter = (loader) => {
    return {
      upload() {
        return new Promise((resolve, reject) => {
          const data = new FormData();
          loader.file.then((file) => {
            data.append('name', file.name);
            data.append('file', file);

            axios
              .post(`${axiosInstance}api/multer/community/upload`, data, {
                headers: { 'content-type': 'multipart/form-data' },
              })
              .then((res) => {
                resolve({
                  default: `${res.data.imagePathName}`,
                });
              })
              .catch((err) => reject(err));
          });
        });
      },
    };
  };

  function uploadPlugin(editor) {
    editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
      return customUploadAdapter(loader);
    };
  }

  return (
    <MainStyle>
      <CKEditor
        editor={ClassicEditor}
        config={{
          extraPlugins: [uploadPlugin],
        }}
        onChange={(event, editor) => {
          const data = editor.getData();
          textDataFun(data);
        }}
      />
    </MainStyle>
  );
};

export default TextEditorInCommunity;

--------------

Node.js

router.post("/community/upload", async (req, res) => {
  const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, `../client/public/img/community`);
    },
    filename: (req, file, cb) => {
      cb(null, `${uuid()}.${mime.extension(file.mimetype)}`);
    },
  });

  const upload = multer({
    storage,
    fileFilter: (req, file, cb) => {
      if (["image/jpeg", "image/jpg", "image/png"].includes(file.mimetype)) cb(null, true);
      else cb(new Error("해당 파일의 형식을 지원하지 않습니다."), false);
    },
    limits: {
      fileSize: 1024 * 1024 * 5,
    },
  }).array("file");

  upload(req, res, (err) => {
    if (err) {
      return res.status(400).json({ success: false, error: err.message });
    }

    const imgs = req.files.map((file) => ({
      fileName: file.filename,
    }));

    return res.json({
      success: true,
      imgs,
      image: req.files[0].path,
      imagePathName: `/img/community/${req.files[0].filename}`,
    });
  });

  router.use(`/img/community`, express.static(path.join(__dirname, `../client/public/img/community`)));
});


#react ckeditor #react ckeditor 사용법 #react ckeditor5 height #react ckeditor 이미지 업로드 #react ckeditor css #react ckeditor plugins #react ckeditor toolbar #react ckeditor config #react ckeditor height #react ckeditor onchange

profile_image 익명 작성일 -

안녕하세요. 답변드립니다.

CKEditor를 사용하여 이미지 업로드 시 페이지가 새로고침되는 문제가 발생하는 것 같습니다. 이 문제를 해결하기 위해 몇 가지 단계를 따라야 합니다. 아래에서 단계별로 설명드리겠습니다:

1. `TextEditorInCommunity` 컴포넌트에서 `customUploadAdapter` 함수를 확인하세요. 이 함수는 이미지 업로드를 처리합니다. 현재 코드에서 이 함수의 반환값은 약속된 형식을 준수하지 않고 있습니다. 반환값이 정확한 형식을 가지도록 수정해야 합니다.

2. `uploadPlugin` 함수에서 CKEditor 플러그인 설정을 확인하세요. 현재 코드에서 `extraPlugins` 설정을 사용하여 `uploadPlugin` 함수를 전달하고 있습니다. 그러나 `uploadPlugin` 함수는 이미지 업로드를 처리할 수 있는 함수를 반환해야 합니다. 이 함수를 수정하여 올바른 형식으로 반환하도록 해야 합니다.

3. Node.js 측에서 이미지 업로드를 처리하는 코드를 확인하세요. 현재 코드에서 `router.post("/community/upload")` 함수가 이미지를 업로드하고 응답을 반환하고 있습니다. 이 코드에서 문제가 발생할 수 있는 부분은 `upload` 함수 내부에서 파일을 저장하는 방식입니다. 파일의 저장 경로와 파일 이름을 제대로 설정하는지 확인해야 합니다.

위의 단계들을 차례대로 따라가면 이미지 업로드 시 페이지가 새로고침되는 문제를 해결할 수 있을 것입니다. 문제가 계속되면 추가적인 정보를 제공해주시면 더 자세한 지원을 드릴 수 있습니다.

도움 되시기 바랍니다.

서버에 배포했는데 이미지 인식 안됨

... 파일 경로 문제: 이미지 파일의 경로가 올바르게... 서버에서 이미지를 처리하는 방식을 확인하세요. 파일 업로드 시, 필요한 폼 필드나 데이터를 올바르게...

웹페이지 이미지 업로드시

... 이미지업로드하면 이미지가 바뀌지를 않습니다. 새로고침 F5를 몇번이고 클릭해도 변하지 않고 인터넷 익스플로러창을 모두 닫고 새로열고 보면 바껴있긴한데 문제는...

asp 이미지 깨짐현상

... 있음 -> 새로고침하면 잘나오거나 다른이미지가 x표시... 때 문제 없다면 걱정 안하셔도 될 듯... x가 뜨는건 먼저 경로가 잘못되지 않았는지, 서버에 업로드는 제대로...