Articles in this section
Category / Section

How to open and save file from server using AJAX call in ASP.NET MVC?

3 mins read

You can open and save a Word document that is available in the web server by using the ASP.NET MVC Document Editor control.

 

CSHTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</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>
            <div>
                <div style=" margin-bottom:12px">
                    @Html.EJS().DropDownButton("fileBtn").Content("Documents").Select("onSelect").Items(ViewBag.filePathInfo).Render()
 
                    @Html.EJS().Button("savebtn").Content("Save Document").IsPrimary(false).Render()
                </div>
                <div style="display:block;width:100%;height:500px">
                    @Html.EJS().DocumentEditorContainer("container").ServiceUrl("/api/DocumentEditor/Import").EnableToolbar(true).Created("onCreated").Render()
                </div>
            </div>
        </div>
    </div>
    @RenderSection("scripts", required: false)
    @Html.EJS().ScriptManager()
</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/Import?fileName=' + fileName, true);
        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();
    }
 
    function saveDocument() {
        documenteditor.saveAsBlob("Docx").then(function (blob) {
            var fileReader = new FileReader();
 
            fileReader.onload = function () {
                var documentData = {
                    fileName: documenteditor.documentName + '.docx',
                    documentData: fileReader.result
                }
                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
    {
        public ActionResult Index()
        {
            ViewBag.filePathInfo = GetFilesInfo();
            return View();
        }
        public List<FilesPathInfo> GetFilesInfo()
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/");
            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

  [HttpPost]
        public HttpResponseMessage Import(string fileName)
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/");
            path += fileName;
            if (!File.Exists(path))
                return null;
            Stream stream = File.OpenRead(path);
            WordDocument document = WordDocument.Load(stream, Syncfusion.EJ2.DocumentEditor.FormatType.Docx);
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
            // Releases unmanaged and optionally managed resources.
            document.Dispose();
            stream.Close();
            return new HttpResponseMessage() { Content = new StringContent(json, Encoding.UTF8, "text/plain") };
        }
        [HttpPost]
        public string Save([FromBody]ExportData exportData)
        {
            Byte[] data = Convert.FromBase64String(exportData.documentData.Split(',')[1]);
            MemoryStream stream = new MemoryStream();
            stream.Write(data, 0, data.Length);
            Syncfusion.EJ2.DocumentEditor.FormatType type = GetFormatType(exportData.fileName);
            stream.Position = 0;
            try
            {
                string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/");
                FileStream fileStream = new FileStream(path + exportData.fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fileStream.Position = 0;
                if (type != Syncfusion.EJ2.DocumentEditor.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.CopyTo(fileStream);
                }
                fileStream.Close();
                stream.Dispose();
                return "Success";
            }
            catch
            {
                return "Failed";
            }
        }
 
        internal static Syncfusion.EJ2.DocumentEditor.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 DocumentEditor does not support this file format.");
            switch (format.ToLower())
            {
                case "dotx":
                case "docx":
                case "docm":
                case "dotm":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Docx;
                case "dot":
                case "doc":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Doc;
                case "rtf":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Rtf;
                case "txt":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Txt;
                case "xml":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.WordML;
                default:
                    throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
            }
        }
 
        internal static Syncfusion.DocIO.FormatType GetDocIOFomatType(Syncfusion.EJ2.DocumentEditor.FormatType type)
        {
            switch (type)
            {
                case Syncfusion.EJ2.DocumentEditor.FormatType.Docx:
                    return Syncfusion.DocIO.FormatType.Docx;
                case Syncfusion.EJ2.DocumentEditor.FormatType.Doc:
                    return Syncfusion.DocIO.FormatType.Doc;
                case Syncfusion.EJ2.DocumentEditor.FormatType.Rtf:
                    return Syncfusion.DocIO.FormatType.Rtf;
                case Syncfusion.EJ2.DocumentEditor.FormatType.Txt:
                    return Syncfusion.DocIO.FormatType.Txt;
                case Syncfusion.EJ2.DocumentEditor.FormatType.WordML:
                    return Syncfusion.DocIO.FormatType.WordML;
                default:
                    throw new NotSupportedException("DocIO does not support this file format.");
            }
        }

 

 

Editing Document

 

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/LoadAndSaveFromServer-1439153959

 

In the previous sample, a dropdown button has been added, which shows a list of files available in ‘App_Data’ in the web server. A document will be opened in the Document Editor control by selecting it.


Conclusion

I hope you enjoyed learning about how to open and save file from server using AJAX call in ASP.NET MVC.

You can refer to our ASP.NET MVC Document Editor 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 ASP.NET MVC Document Editor example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied