Instead of using CKEditor to upload images, I have implemented my own API for image uploading.
When a user uploads an image on my website, I make a call to the API to safely upload the image and return a URL in the Public Domain. The API returns the following object:
{
"uploadedUrls": [
"http://example.com/community/question/insta.jpg",
"http://example.com/community/question/pin.jpg"
]
}
In my Next.js website, the function behind the API works as follows:
const handleUpload = async () => {
const fileInput = document.getElementById('file-upload');
if (fileInput && fileInput.files.length > 0) {
const formData = new FormData();
const files = Array.from(fileInput.files);
files.forEach((file, index) => {
formData.append("files", fileInput.files[index], file.name);
});
formData.append("folderName", "community/question");
try {
const uploadImage = await communityDTO.uploadImage(formData);
if (uploadImage) {
if (typeof uploadImage.uploadedUrls === 'string') {
uploadImage.uploadedUrls = [uploadImage.uploadedUrls];
}
console.log(uploadImage); //This functionality is working perfectly fine
uploadImage.uploadedUrls.map((item)=>(
setInputBody(inputBody + "\n" +
<img className="my-2" src={item} alt={"Image " + item} />
))
);
}
} catch (error) {
console.error('Error:', error);
}
} else {
console.error('No files selected');
}
};
I receive successful results from console.log(uploadImage)
in my console.
Here is how my CKEditor configuration looks like:
<CKEditor
editor={ClassicEditor}
data={inputBody}
onChange={(event, editor) => {
const data = editor.getData();
setInputBody(data); //inputBody uses useState hook
}}
config={{
toolbar: {
items: [
"undo",
"redo",
"|",
"bold",
"italic",
"blockQuote",
"link",
"numberedList",
"bulletedList",
"|",
"heading",
],
shouldNotGroupWhenFull: true,
},
placeholder: "Write your Answer...",
}}
/>
Everything is functioning correctly, and here is how I have declared inputBody:
const [inputBody, setInputBody] = useState("");
Whenever I upload an image, it should be embedded in CKEditor even if multiple images are uploaded...
After successfully uploading an image through the API, I update the inputBody using the following code:
uploadImage.uploadedUrls.map((item)=>(
setInputBody(inputBody + "\n" +
<img className="my-2" src={item} alt={"Image " + item} />
))
);
However, instead of embedding the image, I am getting the result as shown in this output image: Output Image
The result I get is displayed as [object Object]
, rather than showing the image.
(I now understand how stackoverflow handles image uploading using this format
[description](imageurl)
). It would be great if the free version of CKEditor supports this feature. If it does, please suggest it to me. In the meantime, can you help me with my code above?