Category / Section
How to Load/Save File in Web Server for ASP.NET Core DocumentEditor?
3 mins read
You can open and save a Word document that is available in the web server by using the Document Editor control.
CSHTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - ImportExport</title> <link href="https://cdn.syncfusion.com/ej2/fabric.css" rel="stylesheet"> <script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js" type="text/javascript"></script> </head> <body> <div class="container body-content"> <div class="control-section"> <div style=" margin-bottom:12px"> <ejs-dropdownbutton id="fileBtn" items="ViewBag.filePathInfo" select="onSelect" content="Documents"></ejs-dropdownbutton> <ejs-button id="savebtn" content="Save Document" isPrimary="true"></ejs-button> </div> <div style="display:block;width:100%;height:500px"> <ejs-documenteditorcontainer id="container" serviceUrl="/api/DocumentEditor/Import" enableToolbar=true created="onCreated"></ejs-documenteditorcontainer> </div> </div> </div> @RenderSection("Scripts", required: false) <ejs-scripts></ejs-scripts> </body> </html>
JS
<script> document.getElementById("savebtn").addEventListener('click', function () { saveDocument() }); var documenteditor; function onCreated() { var container = document.getElementById("container").ej2_instances[0]; documenteditor = container.documentEditor; documenteditor.resize(); } function onSelect(args) { console.log(args); var fileName = args.item.text; var httpRequest = new XMLHttpRequest(); httpRequest.open('Post', '/api/DocumentEditor/ImportFile', true); httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); httpRequest.onreadystatechange = function () { if (httpRequest.readyState === 4) { if (httpRequest.status === 200 || httpRequest.status === 304) { documenteditor.open(httpRequest.responseText); } else { alert('Fail to load the document'); } } }; documenteditor.documentName = fileName.substr(0, fileName.lastIndexOf('.')); httpRequest.send(JSON.stringify({ "fileName": fileName })); } function saveDocument() { documenteditor.saveAsBlob("Docx").then(function (blob) { var fileReader = new FileReader(); fileReader.onload = function () { var base64Text = ";base64,"; var documentData = { fileName: documenteditor.documentName + '.docx', documentData: fileReader.result.substring(fileReader.result.indexOf(base64Text) + base64Text.length) } var httpRequest = new XMLHttpRequest(); httpRequest.open('Post', '/api/DocumentEditor/Save', true); httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); httpRequest.onreadystatechange = function () { if (httpRequest.readyState === 4) { if (httpRequest.status === 200 || httpRequest.status === 304) { //Sucess } } }; httpRequest.send(JSON.stringify(documentData)); }; fileReader.readAsDataURL(blob); }); } </script>
Controller
public class HomeController : Controller { private IHostingEnvironment hostEnvironment; public HomeController(IHostingEnvironment environment) { this.hostEnvironment = environment; } public IActionResult Index() { ViewBag.filePathInfo = GetFilesInfo(); return View(); } public List<FilesPathInfo> GetFilesInfo() { string path = hostEnvironment.WebRootPath + "\\Files"; return ExplorFiles(path); } // GET: FileExplorer public List<FilesPathInfo> ExplorFiles(string fileDirectory) { List<FilesPathInfo> filesInfo = new List<FilesPathInfo>(); try { foreach (string f in Directory.GetFiles(fileDirectory)) { FilesPathInfo path = new FilesPathInfo(); path.text = Path.GetFileName(f); filesInfo.Add(path); } } catch (System.Exception e) { throw new Exception("error", e); } return filesInfo; } }
WEB API Controller
[Route("api/[controller]")] [ApiController] public class DocumenteditorController : ControllerBase { private IHostingEnvironment hostEnvironment; public DocumenteditorController(IHostingEnvironment environment) { this.hostEnvironment = environment; } [Route("Import")] // Import document uploaded from client side public string Import(IFormCollection data) { if (data.Files.Count == 0) return null; Stream stream = new MemoryStream(); IFormFile file = data.Files[0]; int index = file.FileName.LastIndexOf('.'); string type = index > -1 && index < file.FileName.Length - 1 ? file.FileName.Substring(index) : ".docx"; file.CopyTo(stream); stream.Position = 0; EJ2DocumentEditor.WordDocument document = EJ2DocumentEditor.WordDocument.Load(stream, GetFormatType(type.ToLower())); string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); document.Dispose(); return json; } //Import document from wwwroot folder in web server. [Route("ImportFile")] public string ImportFile([FromBody]CustomParams param) { string path = this.hostEnvironment.WebRootPath + "\\Files\\" + param.fileName; try { Stream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.ReadWrite); Syncfusion.EJ2.DocumentEditor.WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream, GetFormatType(path)); string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); document.Dispose(); stream.Dispose(); return json; } catch { return "Failure"; } } //Save document in wwwroot folder. [Route("Save")] public string Save([FromBody]CustomParameter param) { string path = this.hostEnvironment.WebRootPath + "\\Files\\" + param.fileName; Byte[] byteArray = Convert.FromBase64String(param.documentData); Stream stream = new MemoryStream(byteArray); EJ2DocumentEditor.FormatType type = GetFormatType(path); try { FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (type != EJ2DocumentEditor.FormatType.Docx) { Syncfusion.DocIO.DLS.WordDocument document = new Syncfusion.DocIO.DLS.WordDocument(stream, Syncfusion.DocIO.FormatType.Docx); document.Save(fileStream, GetDocIOFomatType(type)); document.Close(); } else { stream.Position = 0; stream.CopyTo(fileStream); } stream.Dispose(); fileStream.Dispose(); return "Sucess"; } catch { Console.WriteLine("err"); return "Failure"; } } internal static EJ2DocumentEditor.FormatType GetFormatType(string fileName) { int index = fileName.LastIndexOf('.'); string format = index > -1 && index < fileName.Length - 1 ? fileName.Substring(index + 1) : ""; if (string.IsNullOrEmpty(format)) throw new NotSupportedException("EJ2 Document editor does not support this file format."); switch (format.ToLower()) { case "dotx": case "docx": case "docm": case "dotm": return EJ2DocumentEditor.FormatType.Docx; case "dot": case "doc": return EJ2DocumentEditor.FormatType.Doc; case "rtf": return EJ2DocumentEditor.FormatType.Rtf; case "txt": return EJ2DocumentEditor.FormatType.Txt; case "xml": return EJ2DocumentEditor.FormatType.WordML; default: throw new NotSupportedException("EJ2 Document editor does not support this file format."); } } internal static Syncfusion.DocIO.FormatType GetDocIOFomatType(EJ2DocumentEditor.FormatType type) { switch (type) { case EJ2DocumentEditor.FormatType.Docx: return FormatType.Docx; case EJ2DocumentEditor.FormatType.Doc: return FormatType.Doc; case EJ2DocumentEditor.FormatType.Rtf: return FormatType.Rtf; case EJ2DocumentEditor.FormatType.Txt: return FormatType.Txt; case EJ2DocumentEditor.FormatType.WordML: return FormatType.WordML; default: throw new NotSupportedException("DocIO does not support this file format."); } } }
Model
public class CustomParams { public string fileName { get; set; } } public class CustomParameter { public string fileName { get; set; } public string documentData { get; set; } }
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/ImportAndExport-1834481218
In the previous sample, a dropdown button has been added, which shows a list of files available in ‘wwwroot/Files’ folder in the web server. A document will be opened in the Document Editor control by selecting it.