imageUploadUrl SunEditor in Next.js

1.9k Views Asked by At

I want to ask because after a few days I haven't found a way to upload files to the API. I use suneditor for editor in my Next.js project. I want that when I upload an image, the image will be sent to the API https://api-my.com/v1/file-uploads or /file-uploads with a field that is file.

I have tried using this method, but it doesn't work.

imageUploadUrl: (file, callback) => {
    const formData = new FormData();
    formData.append("file", file);
    axiosInstance({
      url: "/file-uploads",
      method: "POST",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
        Accept: "application/json",
      },
    }).then((res) => {
      callback(res.data.url);
    });
},
2

There are 2 best solutions below

0
On

That's because that option it's waiting for a string and not a function, in any case you can use the server url server.url/file-uploads to upload the images.

0
On

After setup SunEditor then if you upload any image then it will take default base64 data format, In production we need to use our custom api for host images.

For this, we have a method onImageUploadBefore Below I have share my component that work in my react app, You can try same thing in next.js

remember: in next.js you should use import SunEditor dynamically, example below

import dynamic from "next/dynamic";
const Editor = dynamic(() => import("suneditor-react"), {
  ssr: false,
});
import axios from "axios";
import { useRef } from "react";
import Editor from "suneditor-react";

export default function TestSunEditorJsx() {
  const editor = useRef();

  const getSunEditorInstance = (sunEditor) => {
    editor.current = sunEditor;
  };

  function onImageUploadBefore() {
    return (files, _info, _core, uploadHandler) => {
      (async () => {
        const formData = new FormData();
        formData.append("file", files[0]);

        const { data } = await axios.post(
          "http://localhost:1000/api/v1/upload/single",
          formData
        );

        const res = {
          result: [
            {
              url: data?.url,
              name: "thumbnail",
            },
          ],
        };

        uploadHandler(res);
      })();

      // called here for stop double image
      uploadHandler();
    };
  }

  return (
    <Editor
      getSunEditorInstance={getSunEditorInstance}
      onImageUploadBefore={onImageUploadBefore()}
      setOptions={{
        buttonList: [["image"]],
      }}
      height="50vh"
    />
  );
}