Как сначала загрузить изображение на сервер из текстового редактора ReactQuill с помощью обработчика изображений

Вот как код выглядит на странице

      import { SyncOutlined, CameraFilled, LoadingOutlined } from "@ant-design/icons";
import React, { useState, useEffect, useRef } from "react";
import { Avatar } from "antd";
//import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import "react-quill/dist/quill.core.css";
import "react-quill/dist/quill.bubble.css";
import "quill-image-uploader/dist/quill.imageUploader.min.css";
import axios from "axios";
import dynamic from "next/dynamic";

const ReactQuill = dynamic(() => import("react-quill"), { ssr: false });
const Quill = dynamic(() => import("quill"), { ssr: false });

const CreatePostForm = ({
  postUpload,
  postSubmit,
  content,
  setContent,
  loading,
  handleImage2,
  placeholder,
  uploading,
  image,
}) => {

  const quillRef = useRef();

  const [image2, setImage2] = useState({});
  const [theme, setTheme] = useState("snow");
  const handleThemeChange = (newTheme) => {
    if (newTheme === "bubble") {
      -setTheme("bubble");
    }
    if (newTheme === "snow") {
      setTheme("snow");
    }
  };
  

  const imageHandler = () => {
    const input = document.createElement("input");

    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.click();
    console.log(input);
    console.log(new FormData());
    input.onChange = async (e) => {
      const file = e.target.files[0];
      //console.log(file);
      const formData = new FormData();
      console.log([...formData]);
      formData.append("image", file);
      console.log([...formData]);
      
      const quill = quillRef.current.getEditor();
      console.log(quill);
      const range = quill.getSelection(true);

      // Insert temporary loading placeholder image
      quill.insertEmbed(
        range.index,
        "image",
        `${window.location.origin}/images/loaders/placeholder.gif`
      );

      // Move cursor to right side of image (easier to continue typing)
      quill.setSelection(range.index + 1);
      try {
        const { data } = await axios.post("/uploadImage", formData);
        if (data.error) {
          toast.error(data.error);
        }
        console.log("uploaded image=>", data);
        setImage2({
          url: data.url,
          public_id: data.public_id,
        });
        quill.deleteText(range.index, 1);

        // Insert uploaded image
        
        quill.insertEmbed(range.index, "image", data.url);
        console.log(quill);
      } catch (err) {
        console.log(err);
      }
      
    };
  };
  let modules = {
    toolbar: {
      container: [
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        ["bold", "italic", "underline"],
        [{ font: [] }],
        [{ size: [] }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ align: [] }],
        [
          "link",
          "image", "video"
        ],
        ["clean"],
        [{ color: [] }],
      ],
       handlers: {
         image: imageHandler,
       },
    },
  };
  const formats = [
    "header",
    "font",
    "size",
    "bold",
    "italic",
    "underline",
    "strike",
    "blockquote",
    "list",
    "bullet",
    "indent",
    "link",
    "image",
    "video",
  ];


  return (
    <div className="card ">
      <div className="card-body">
        <form className="form-group" onSubmit={postSubmit}>
          <hr />
          <ReactQuill
            ref={quillRef}
            value={content}
            onChange={(e) => setContent(e)}
            className="form-control"
            theme={"snow"}
            placeholder="Write Something..."
            modules={modules}
            formats={formats}
            preserveWhitespace={true}
          />
  

          
          <div className="card-footer d-flex  text-muted">
            <label className=" justify-content-left m-2 py-2">
              {image && image.url ? (
                <Avatar size={30} src={image.url} className="mt-1" />
              ) : uploading ? (
                <LoadingOutlined className="size py-2" />
              ) : (
                <CameraFilled className="size py-2" />
              )}

              <input
                type="File"
                className=" m-2 py-2"
                accept="images/*"
                onChange={handleImage2}
                hidden
              />
            </label>
            <div className="justify-content-end">
              <button
                onClick={postUpload}
                className="btn-lg btn btn-success py-2 m-2"
              >
                RESET
              </button>

              {/*  */}

              <button
                disabled={!content && !image}
                className="btn-lg btn btn-success py-2 m-2"
                type="submit"
                onClick={postSubmit}
              >
                {loading ? <SyncOutlined spin className="py-1" /> : "POST"}
              </button>
            </div>
          </div>
        </form>
      </div>
      <script src="/dist/quill.js"></script>
      <script src="/dist/quill.imageUploader.min.js"></script>
    </div>
  );
};
export default CreatePostForm;

Одна ошибка, которую я получаю в этом коде при запуске диапазона. Как определить quillRef, который является эталонным экземпляром ReactQuill. Я тоже искал решение в чатгпте или барде, но ни один из них, похоже, не работает.

Я пытаюсь добавить обработчик изображения к значку изображения на панели инструментов ReactQuill, чтобы, пока я нажимаю значок изображения на панели инструментов и выбираю и открываю изображение, изображение можно загрузить на сервер, который определен в конечной точке, и визуализировать изображение из URL-адреса ответа в редакторе, на который указывает курсор.

0 ответов

Другие вопросы по тегам