react-draft-wysiwyg 图像的 base64 转换从上传图像字段溢出。

huangapple go评论75阅读模式
英文:

react-draft-wysiwyg The converted base64 for image is overflowing from the upload image field

问题

以下是您要翻译的内容:

I have a working react-draft-wysiwyg editor application. I am able to add images to editor using this. There is one issue i am facing, please check this below:

react-draft-wysiwyg 图像的 base64 转换从上传图像字段溢出。

Here's the code so far what i've tried. And note that for display purpose even if i pass truncatedUrl inside callback the error is "Invalid URL passed",

So basically what i am trying to do is show some small string inside the "File Upload" Box but when i click on "Add" the complete image URL needs to be passed.

Here's what i've tried so far:

import {Editor} from "react-draft-wysiwyg";
import { EditorState, ContentState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const [editorState, setEditorState] = useState(EditorState.createEmpty());

useEffect(() => {
    let html = stateToHTML(editorState.getCurrentContent());
    setContent(html);
}, [editorState]);

const handleEditorChange = (state) => {
    setEditorState(state);
    const selectedBlock = state.getCurrentContent().getBlockForKey(
      state.getSelection().getStartKey()
    );
    const selectedEntity = selectedBlock.getEntityAt(
      state.getSelection().getStartOffset()
    );
    if (selectedEntity !== null) {
      if (typeof selectedEntity.getData === 'function') { // add this check
        const image = selectedEntity.getData().url;
        setImageFile(image); // remove data URL prefix
      } else {
        console.error('selectedEntity does not have getData method');
      }
    } else {
      setImageFile(null);
    }
};

const addLesson = async () => {
    setIsUploading(true);

    try {
      const formData = new FormData();
      formData.append('name', title);
      formData.append('content_type', contentType);
      if (contentType === 'text' && content) {
        formData.append('content', content);
      }
      if (contentType === 'video' && video) {
        formData.append('content', video);
      }
      formData.append('course_id', course_id);
      formData.append("imageFile", imageFile);

      const response = await axios.post(url() + 'api/admin/lessons', formData);
      if (response?.status === 200) {
        setSuccess('Lesson successfully added.');
        window.setTimeout(() => {
          history.push(`/course/${course_id}/lessons`);
        }, 1000);
      }
    } catch (error) {
      console.error(error);
      setError(error?.response?.data?.msg);
    }

    setIsUploading(false);
};

return (
   <div className="row m-3">
                <h6 className="edit-box-label ml-2">Lesson Content</h6>
                <div className="col-xl-12">
                   <Editor
                     editorState={editorState}
                     onEditorStateChange={handleEditorChange}
                    toolbar={{
                      image: {
                        uploadCallback: (file) => {
                          return new Promise((resolve, reject) => {
                            const reader = new FileReader();
                            reader.readAsDataURL(file);
                            reader.onload = () => {
                              const dataURL = reader.result;
                              const truncatedDataURL = dataURL.substring(10, 30) + "..."; // set the maximum length of the truncated string
                              resolve({ data: { link: dataURL }, link: { url: truncatedDataURL } });
                            };
                            reader.onerror = (error) => {
                              reject(error);
                            };
                          });
                        },
                        alt: { present: true, mandatory: false }
                      }
                    }}
                   />
                </div>
              </div>
)

Requesting help regarding this, all your efforts are appreciated.

Regards,

英文:

I have a working react-draft-wysiwyg editor application. I am able to add images to editor using this. There is one issue i am facing , please check this below :

react-draft-wysiwyg 图像的 base64 转换从上传图像字段溢出。

Here's the code so far what i've tried. And note that for display purpose even if i pass truncatedUrl inside callback the error is "Invalid URL passed" ,

So basically what i am trying to do is show some small string inside the "File Upload" Box but when i click on "Add" the complete image URL needs to be passed.

Here's what i've tried so far:

import {Editor} from &quot;react-draft-wysiwyg&quot;;
import { EditorState, ContentState } from &quot;draft-js&quot;;
import &quot;react-draft-wysiwyg/dist/react-draft-wysiwyg.css&quot;;
const [editorState, setEditorState] = useState(EditorState.createEmpty())
useEffect(() =&gt; {
let html = stateToHTML(editorState.getCurrentContent())
setContent(html)
}, [editorState])
const handleEditorChange = (state) =&gt; {
setEditorState(state);
const selectedBlock = state.getCurrentContent().getBlockForKey(
state.getSelection().getStartKey()
);
const selectedEntity = selectedBlock.getEntityAt(
state.getSelection().getStartOffset()
);
if (selectedEntity !== null) {
if (typeof selectedEntity.getData === &#39;function&#39;) { // add this check
const image = selectedEntity.getData().url;
setImageFile(image); // remove data URL prefix
} else {
console.error(&#39;selectedEntity does not have getData method&#39;);
}
} else {
setImageFile(null);
}
};
const addLesson = async () =&gt; {
setIsUploading(true);
try {
const formData = new FormData();
formData.append(&#39;name&#39;, title);
formData.append(&#39;content_type&#39;, contentType);
if (contentType === &#39;text&#39; &amp;&amp; content) {
formData.append(&#39;content&#39;, content);
}
if (contentType === &#39;video&#39; &amp;&amp; video) {
formData.append(&#39;content&#39;, video);
}
formData.append(&#39;course_id&#39;, course_id);
formData.append(&quot;imageFile&quot;, imageFile);
const response = await axios.post(url() + &#39;api/admin/lessons&#39;, formData);
if (response?.status === 200) {
setSuccess(&#39;Lesson successfully added.&#39;);
window.setTimeout(() =&gt; {
history.push(`/course/${course_id}/lessons`);
}, 1000);
}
} catch (error) {
console.error(error);
setError(error?.response?.data?.msg);
}
setIsUploading(false);
};
return (
&lt;div className=&quot;row m-3&quot;&gt;
&lt;h6 className=&quot;edit-box-label ml-2&quot;&gt;Lesson Content&lt;/h6&gt;
&lt;div className=&quot;col-xl-12&quot;&gt;
&lt;Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
toolbar={{
image: {
uploadCallback: (file) =&gt; {
return new Promise((resolve, reject) =&gt; {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () =&gt; {
const dataURL = reader.result;
const truncatedDataURL = dataURL.substring(10, 30) + &quot;...&quot;; // set the maximum length of the truncated string
resolve({ data: { link: dataURL } , link : { url : truncatedDataURL} });
};
reader.onerror = (error) =&gt; {
reject(error);
};
});
},
alt: { present: true, mandatory: false }
}
}}
/&gt;
&lt;/div&gt;
&lt;/div&gt;
)

Requesting help regarding this , all your efforts are appreciated.

Regards,

答案1

得分: 1

添加属性图像

toolbar={{
  image: {
    "previewImage": true,
    ...,
  },
  ...
}}

用于将您的Base64预览转换为图像预览。

英文:

Add props image

toolbar={{
image:{
&quot;previewImage&quot;: true,
...,
},
...
}}

for convert your base64 preview to image preview

huangapple
  • 本文由 发表于 2023年3月7日 13:48:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定