Insert or drag and drop images from local system to RichTextEditor
Description:
To insert or drag and drop images from local system through UploadBox to RichTextEditor.
Solution:
Add a button as custom tool for RichTextEditor. By clicking this button, open a dialog box with ejUploadBox. Enable the drag and drop property in ejUploadBox by setting allowDragAndDrop to true.
<div> <textarea id="rteSample" rows="10" cols="30"> </textarea> </div> <div id="Dialog1" title="Insert Image"> <div id="UploadDefault"></div> </div>
|
<script type="text/javascript"> var rteObj,uploadObj,diaObj,attr; $(function () { $("#Dialog1").ejDialog({ width:"600px", height:"300px",enableResize:false, showOnInit:false , create:function(args){ diaObj= this;}}); $("#UploadDefault").ejUploadbox({ saveUrl: "https://js.syncfusion.com/demos/web/uploadbox/saveFiles.ashx", removeUrl:"https://js.syncfusion.com/demos/web/uploadbox/removeFiles.ashx", extensionsAllow: ".jpg,.png", multipleFilesSelection: false, dialogPosition: { X: 270, Y: 10 }, allowDragAndDrop: true, buttonText: { upload: "Insert Image"}, dialogAction:{closeOnComplete:true}, create:function(args) { uploadObj=this; }, success: "onSuccess", fileSelect:"onfileSelect" }); $("#rteSample").ejRTE({ width: "100%", minWidth: "150px", cssClass: "custom", isResponsive:true, toolsList: ["formatStyle", "font","customTools", "style", "media","images" ], tools: { formatStyle: ["format"], font: ["fontName", "fontSize"], style: ["bold", "italic"], media: ["video"], images: ["image"], customTools: [{ name: "InsertImage", tooltip: "InsertImage ", css: "InsertImage" }] } });
//Add text for custom tool bar element. $("div.InsertImage").html("").attr("id", "InsertImage"); $("#InsertImage").ejButton( { click:"onclick", width:"100px", text:"InsertImage" });
rteObj = $("#rteSample").data("ejRTE"); }); function onclick(args) { diaObj.open(); } </script> |
Now, drag the images from local and drop in the drop area. Read an image details through the fileSelect event of UploadBox using FileReader.
function onfileSelect(args) { var file = args.files[0].rawFile; var reader = new FileReader(); reader.onload = function (event) { attr = event.target.result; }; reader.readAsDataURL(file); }
|
This will return the base64 encoded string which can be added as “src” attribute for the uploaded image in success event. Now the final image can be inserted through “inserthtml” command of RichTextEditor.
function onSuccess(args) { rteObj = $("#rteSample").data("ejRTE"); var image = ej.buildTag("img#image"); image.attr("src", attr); rteObj.executeCommand("inserthtml", image[0].outerHTML); diaObj.close(); }
|
JSPlayground sample: https://jsplayground.syncfusion.com/zf2kayte