reactjs Next.js中的imageUploadUrl SunEditor

eblbsuwk  于 2023-06-22  发布在  React
关注(0)|答案(2)|浏览(92)

我想问一下,因为几天后我还没有找到一种方法来上传文件到API。我在Next.js项目中使用suneditor作为编辑器。我希望当我上传图像时,图像将被发送到API https://api-my.com/v1/file-uploads或/file-uploads,其字段为file。
我试过用这个方法,但不管用。

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);
    });
},
5kgi1eie

5kgi1eie1#

这是因为该选项等待的是字符串而不是函数,在任何情况下,您可以使用服务器url server.url/file-uploads上传图像。

kt06eoxx

kt06eoxx2#

安装SunEditor后,如果您上传任何图像,则它将采用默认的base64数据格式,在生产中,我们需要使用我们的自定义API用于主机图像。
为此,我们有一个方法onImageUploadBefore下面我分享了我在我的React应用程序中工作的组件,你可以在next.js中尝试同样的事情
remember:在next.js中,您应该动态地使用import SunEditor,示例如下

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"
    />
  );
}

相关问题