How to Auto Save Document in ASP.NET MVC DOCX Editor
27 Aug 20266 minutes to read
In this article, we are going to see how to auto save the document to server. You can automatically save the edited content in regular intervals of time. It helps reduce the risk of data loss by saving an open document automatically at customized intervals.
The following example illustrates how to auto save the document on the server.
- In the client-side, using content change event, we can automatically save the edited content in regular intervals of time. Based on
contentChangedboolean, the document is sent as DOCX format to server-side using [saveAsBlob] method.
@Html.EJS().DocumentEditorContainer("container").Created("onCreate").EnableToolbar(true).Render()
<script>
var container;
var containerPanel;
var contentChanged =false;
document.addEventListener('DOMContentLoaded', function () {
var documenteditorElement = document.getElementById("container");
container = documenteditorElement.ej2_instances[0];
container.contentChange=function(){
contentChanged = true;
}
});
function onCreate() {
var documenteditorElement = document.getElementById("container");
container = documenteditorElement.ej2_instances[0];
setInterval(() => {
if (contentChanged) {
//You can save the document as below
container.documentEditor.saveAsBlob('Docx').then((blob) => {
console.log('Saved sucessfully');
let exportedDocument = blob;
//Now, save the document where ever you want.
let formData = new FormData();
formData.append('fileName', 'sample.docx');
formData.append('data', exportedDocument);
/* tslint:disable */
var req = new XMLHttpRequest();
// Replace your running Url here
req.open(
'POST',
'http://localhost:62869/api/documenteditor/AutoSave',
true
);
req.onreadystatechange = () => {
if (req.readyState === 4) {
if (req.status === 200 || req.status === 304) {
console.log('Saved sucessfully');
}
}
};
req.send(formData);
});
contentChanged = false;
}
}, 1000);
}
</script>- On the server-side, receive the stream content from client-side and persist it to the server or a database. Add Web API in controller file like below to save the document.
[AcceptVerbs("Post")]
[HttpPost]
[EnableCors("AllowAllOrigins")]
[Route("AutoSave")]
public string AutoSave()
{
IFormFile file = HttpContext.Request.Form.Files[0];
Stream stream = new MemoryStream();
file.CopyTo(stream);
//Save the stream to database or server as per the requirement.
stream.Close();
return "Success";
}Online Demo
Explore how to automatically save Word documents using the ASP.NET MVC DOCX Editor in this ASP.NET MVC DOCX Editor live demo.