Audio in EJ2 JavaScript Rich text editor control
29 Aug 202324 minutes to read
The Rich Text Editor allows you to insert audio from online sources and local computers and then insert them into your content. You can insert the audio with the following list of options in the insertAudioSettings property.
Options | Description |
---|---|
allowedTypes | Specifies the extensions of the audio types allowed to insert on bowering and passing the extensions with comma separators. For example, pass allowedTypes as .mp3 , .wav , .m4a and .wma . |
layoutOption | Sets the default display for audio when it is inserted into the Rich Text Editor. Possible options are: Inline and Break . |
saveFormat | Sets the default save format of the audio element when inserted. Possible options are: Blob and Base64 . |
saveUrl | Provides URL to map the action result method to save the audio. |
removeUrl | Provides URL to map the action result method to remove the audio. |
path | Specifies the location to store the audio. |
Configure audio tool in the toolbar
You can add an audio
tool in the Rich Text Editor toolbar using the toolbarSettings
items property.
To configure the Audio
toolbar item, refer to the below code.
/**
* Rich Text Editor - RemoveUrl sample
*/
var defaultRTE = new ej.richtexteditor.RichTextEditor({
insertAudioSettings: {
saveUrl: 'https://ej2.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://ej2.syncfusion.com/services/api/uploadbox/Remove'
},
toolbarSettings: {
items: ['Audio']
}
});
defaultRTE.appendTo('#defaultRTE');
<!DOCTYPE html><html lang="en"><head>
<title>Essential JS 2 Rich Text Editor</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Typescript UI Controls">
<meta name="author" content="Syncfusion">
<link href="index.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-inputs/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-lists/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-richtexteditor/styles/material.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/27.1.48/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
<div id="container">
<div id="defaultRTE">
<p>The Rich Text Editor is WYSIWYG ("what you see is what you get") editor useful to create and edit content, and return the valid <a href="https://ej2.syncfusion.com/home/" target="_blank">HTML markup</a> or <a href="https://ej2.syncfusion.com/home/" target="_blank">markdown</a> of the content</p>
<p><b>Key features:</b></p>
<ul>
<li><p>Provides <IFRAME> and <DIV> modes</p></li>
<li><p>Capable of handling markdown editing.</p></li>
<li><p>Contains a modular library to load the necessary functionality on demand.</p></li>
<li><p>Provides a fully customizable toolbar.</p></li>
<li><p>Provides HTML view to edit the source directly for developers.</p></li>
<li><p>Supports third-party library integration.</p></li>
<li><p>Allows preview of modified content before saving it.</p></li>
<li><p>Handles images, hyperlinks, video, hyperlinks, uploads, etc.</p></li>
</ul>
</div>
</div>
<script>
var ele = document.getElementById('container');
if(ele) {
ele.style.visibility = "visible";
}
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>
Insert audio from the web
You can insert audio from either the hosted link or the local machine, by clicking the audio button in the editor’s toolbar. On clicking the audio button, a dialog opens, which allows you to insert audio from the web URL.
Insert from web URL
By default, the audio tool opens the audio dialog, allowing you to insert audio from an online source. Inserting the URL will be added to the src
attribute of the <source>
tag.
Insert audio from local machine
You can use the browse
option on the audio dialog, to select the audio from the local machine and insert it into the Rich Text Editor content.
If the path field is not specified in the insertAudioSettings, the audio will be converted into the Blob
URL or Base64
and inserted inside the Rich Text Editor.
Restrict audio upload based on size
You can restrict the audio uploaded from the local machine when the uploaded audio file size is greater than the allowed size by using the fileUploading event.
The file size in the argument will be returned in
bytes
.
In the following illustration, the audio size has been validated before uploading, and it is determined whether the audio has been uploaded or not.
<script>
var defaultRTE = new new ej.richtexteditor.RichTextEditor({
toolbarSettings: {
items: ['Audio']
},
insertAudioSettings: {
saveUrl: "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save",
path: "../Files/"
},
fileUploading: onFileUpload
});
defaultRTE.appendTo('#defaultRTE');
function onFileUpload (args) {
var sizeInBytes = args.fileData.size;
var fileSize = 500000;
if (fileSize < sizeInBytes) {
args.Cancel = true;
}
}
</script>
Server-side action
The selected audio can be uploaded to the required destination using the controller action below. Map this method name in insertAudioSettings.saveUrl and provide the required destination path through insertAudioSettings.path properties.
If you want to insert lower-sized audio files in the editor and don’t want a specific physical location for saving the audio, you can opt to save the format as
Base64
.
In the following code blocks, the audio module has been injected and can insert the audio files saved in the specified path.
<script>
var defaultRTE = new ej.richtexteditor.RichTextEditor({
toolbarSettings: {
items: ['Audio']
},
insertAudioSettings: {
saveUrl: "[SERVICE_HOSTED_PATH]/api/uploadbox/SaveFiles",
path: "[SERVICE_HOSTED_PATH]/Files/"
}
});
defaultRTE.appendTo('#defaultRTE');
</script>
using System;
using System.IO;
using FileUpload.Models;
using System.Diagnostics;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
namespace FileUpload.Controllers
{
public class HomeController : Controller
{
private IHostingEnvironment hostingEnv;
public HomeController(IHostingEnvironment env)
{
hostingEnv = env;
}
public IActionResult Index()
{
return View();
}
[AcceptVerbs("Post")]
public void SaveFiles(IList<IFormFile> UploadFiles)
{
try
{
foreach (IFormFile file in UploadFiles)
{
if (UploadFiles != null)
{
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = hostingEnv.WebRootPath + "\\Files" + $@"\{filename}";
// Create a new directory, if it does not exists
if (!Directory.Exists(hostingEnv.WebRootPath + "\\Files"))
{
Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Files");
}
if (!System.IO.File.Exists(filename))
{
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
Response.StatusCode = 200;
}
}
}
}
catch (Exception)
{
Response.StatusCode = 204;
}
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Audio save format
The audio files can be saved as Blob
or Base64
URL by using the insertAudioSettings.saveFormat property, which is of enum type, and the generated URL will be set to the src
attribute of the <source>
tag.
The default
saveFormat
property is set toBlob
format.
<audio>
<source src="blob:http://ej2.syncfusion.com/3ab56a6e-ec0d-490f-85a5-f0aeb0ad8879" type="audio/mp3" >
</audio>
<audio>
<source src="data:audio/mp3;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHA" type="audio/mp3" >
</audio>
Replacing audio
Once an audio file has been inserted, you can change it using the Rich Text Editor quickToolbarSettings audioReplace
option. You can replace the audio file using the web URL or the browse option in the audio dialog.
Delete audio
To remove audio from the Rich Text Editor content, select the audio and click the audioRemove
button from the quick toolbar. It will delete the audio from the Rich Text Editor content as well as from the service location if the insertAudioSettings.removeUrl is given.
Once you select the audio from the local machine, the URL for the audio will be generated. You can remove the audio from the service location by clicking the cross icon.
Display position
Sets the default display property for audio when it is inserted in the Rich Text Editor using the insertAudioSettings.layoutOption property. It has two possible options: Inline
and Break
. When updating the display positions, it updates the audio elements’ layout position.
The default
layoutOption
property is set toInline
.
var defaultRTE = new ej.richtexteditor.RichTextEditor({
insertAudioSettings: {
layoutOption: 'Inline'
}
});
defaultRTE.appendTo('#defaultRTE');
Rename audio before inserting
You can use the insertAudioSettings property, to specify the server handler to upload the selected audio. Then by binding the fileUploadSuccess event, you can receive the modified file name from the server and update it in the Rich Text Editor’s insert audio dialog.
<div id='defaultRTE'>
<p>The Rich Text Editor is WYSIWYG ("what you see is what you get") editor useful to create and edit content, and return the valid <a href="https://ej2.syncfusion.com/home/" target="_blank">HTML markup</a> or <a href="https://ej2.syncfusion.com/home/" target="_blank">markdown</a> of the content</p>
</div>
<script>
var defaultRTE = new ej.richtexteditor.RichTextEditor({
toolbarSettings: {
items: ['Audio']
},
insertAudioSettings: {
saveUrl: "[SERVICE_HOSTED_PATH]/api/uploadbox/Rename",
path: "[SERVICE_HOSTED_PATH]/Files/"
},
fileUploadSuccess: onFileUploadSuccess
});
defaultRTE.appendTo('#defaultRTE');
function onFileUploadSuccess (args) {
alert("Get the new file name here");
if (args.e.currentTarget.getResponseHeader('name') != null) {
args.file.name = args.e.currentTarget.getResponseHeader('name');
var filename = document.querySelectorAll(".e-file-name")[0];
filename.innerHTML = args.file.name.replace(document.querySelectorAll(".e-file-type")[0].innerHTML, '');
filename.title = args.file.name;
}
}
</script>
To configure server-side handler, refer to the below code.
int x = 0;
string file;
[AcceptVerbs("Post")]
public void Rename()
{
try
{
var httpPostedFile = System.Web.HttpContext.Current.Request.Files["UploadFiles"];
fileName = httpPostedFile.FileName;
if (httpPostedFile != null)
{
var fileSave = System.Web.HttpContext.Current.Server.MapPath("~/Files");
if (!Directory.Exists(fileSave))
{
Directory.CreateDirectory(fileSave);
}
var fileName = Path.GetFileName(httpPostedFile.FileName);
var fileSavePath = Path.Combine(fileSave, fileName);
while (System.IO.File.Exists(fileSavePath))
{
fileName = "rteFiles" + x + "-" + fileName;
fileSavePath = Path.Combine(fileSave, fileName);
x++;
}
if (!System.IO.File.Exists(fileSavePath))
{
httpPostedFile.SaveAs(fileSavePath);
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.Headers.Add("name", fileName);
Response.ContentType = "application/json; charset=utf-8";
Response.StatusDescription = "File uploaded succesfully";
Response.End();
}
}
}
catch (Exception e)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusCode = 204;
Response.Status = "204 No Content";
Response.StatusDescription = e.Message;
Response.End();
}
}
Upload audio with authentication
You can add additional data with the audio uploaded from the Rich Text Editor on the client side, which can even be received on the server side by using the fileUploading event and its customFormData
argument, you can pass parameters to the controller action. On the server side, you can fetch the custom headers by accessing the form collection from the current request, which retrieves the values sent using the POST method.
By default, it doesn’t support the
UseDefaultCredentials
property; we need to manually append the default credentials with the upload request.
<script>
var defaultRTE = new ej.richtexteditor.RichTextEditor({
toolbarSettings: {
items: ['Audio']
},
insertAudioSettings: {
saveUrl: "[SERVICE_HOSTED_PATH]/api/uploadbox/SaveFiles",
path: "[SERVICE_HOSTED_PATH]/Files/"
},
fileUploading: onFileUpload
});
defaultRTE.appendTo('#defaultRTE');
function onFileUpload (args) {
var accessToken = "Authorization_token";
// adding custom Form Data
args.customFormData = [{ 'Authorization': accessToken }];
}
</script>
public void SaveFiles(IList<IFormFile> UploadFiles)
{
string currentPath = Request.Form["Authorization"].ToString();
}