Adding File Attachments in React Rich Text Editor
The React Rich Text Editor does not natively support file attachments. However, you can implement this functionality by utilizing the Uploader Component along with the executeCommand
method to insert HTML into the Rich Text Editor. Below is a guide on how to achieve this.
Initializing Rich Text Editor with Custom Tool
Initialize the Rich Text Editor with the necessary toolbar items and add a custom tool using the template option in the toolbarSettings property that includes a button for file attachment.
<RichTextEditorComponent toolbarSettings={toolbarSettings}
created={onCreate.bind(this)}>
</RichTextEditorComponent>
const toolbarSettings = {
items: items,
};
const items = [
// Other toolbar items...
{
tooltipText: 'File Upload',
template:
'<button class="e-tbar-btn e-btn" tabindex="-1" id="custom_tbar" style="width:100%"><div class="e-tbar-btn-text" style="font-weight: 500;">File Attachment</div></button>',
},
// Other toolbar items...
];
Configuring the Uploader Component Inside a Dialog
Integrate the Uploader component as content within the Dialog component, so that when the custom toolbar button is clicked, a dialog opens containing the uploader. This allows users to add file attachments directly within the Rich Text Editor.
<DialogComponent
id="customTbarDlg"
ref={(scope) => {
dialogObj = scope;
}}
buttons={dlgButtons}
header={header}
visible={false}
showCloseIcon={true}
target={'#rteSection'}>
<div>
File Upload
{/* Render Uploader */}
<UploaderComponent
id="UploadFiles"
type="file"
showFileList="false"
ref={(scope) => {
uploadObj = scope;
}}
success={success}
asyncSettings={asyncSettings}
></UploaderComponent>
</div>
</DialogComponent>
Implementing File Attachments
When the custom file attachment custom toolbar button is clicked, a Dialog component is displayed containing the Uploader component for file uploads. After a file is successfully uploaded, you can retrieve the file details using the uploader’s success event. Upon clicking the Insert button in the dialog, use the executeCommand method to insert the file link into the Rich Text Editor.
Here is a code snippet,
const asyncSettings = {
saveUrl: '[SERVICE_HOSTED_PATH]/api/RichTextEditor/Save/',
removeUrl: '[SERVICE_HOSTED_PATH]/Files/',
};
function onCreate() {
const customBtn = document.getElementById('custom_tbar');
customBtn.onclick = (e) => {
rteObj.contentModule.getEditPanel().focus();
dialogObj.element.style.display = '';
range = selection.getRange(document);
saveSelection = selection.save(range, document);
dialogObj.content = rteSpecialCharEle;
dialogObj.show();
};
}
function success(args) {
link =
'<a href=https://localhost:7021/Files/' +
args.file.name +
' download>' +
args.file.name +
'</a>';
}
function onInsert() {
if (link) {
uploadObj.clearAll();
if (rteObj.formatter.getUndoRedoStack().length === 0) {
rteObj.formatter.saveData();
}
saveSelection.restore();
rteObj.executeCommand('insertHTML', link);
rteObj.formatter.saveData();
rteObj.formatter.enableUndo(rteObj);
}
dialogOverlay();
}
Server-Side Code
To handle file uploads on the server side, you can use the following code snippet:
[HttpPost("[action]")]
[Route("api/Image/Save")]
public void Save(IList<IFormFile> UploadFiles)
{
try
{
foreach (var file in UploadFiles)
{
if (UploadFiles != null)
{
string targetPath = _webHostEnvironment.ContentRootPath + "\\wwwroot\\Files";
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
// Create a new directory if it does not exist
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
filename = targetPath + $@"\{filename}";
if (!System.IO.File.Exists(filename))
{
// Upload the file if the same file name does not exist in the directory
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
Response.StatusCode = 200;
Response.ContentType = "application/json; charset=utf-8";
}
else
{
Response.StatusCode = 204; // No content
}
}
}
}
catch (Exception e)
{
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
Conclusion
I hope you enjoyed learning how to add file attachments in the React Rich Text Editor
You can refer to the React RichTextEditor feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React RichTextEditor example to understand how to create and manipulate data.