In this article I will explain with an example, how to upload and display Word files from Database inside View in ASP.Net Core MVC.
The Word (Docx) File will be displayed in Browser using the docx-preview.js JavaScript plugin.
This article will also illustrate how to insert Word (Docx) file in SQL Server Database Table in ASP.Net Core MVC.
 
 
docx-preview.js plugin
The Word (Docx) file will be displayed (rendered) in Browser using docx-preview.js JavaScript plugin.
Note: This library only works for Word 2007 and higher formats (docx) and not the Word 97 – 2003 formats (doc).
 
The following files JavaScript plugin will be used.
1. docx-preview.js
2. jszip.min.js
 
 
Database
This article makes use of a table named tblFiles whose schema is defined as follows.
ASP.Net Core MVC: Display Word files from Database in View
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
 
 
Model
The following Model class consists of the following properties needed for inserting and populating the records of the Files from database.
public class FileModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ContentType { get; set; }
    public byte[] Data { get; set; }
}
 
 
Controller
The Controller consists of three Action methods.
Action method for handling GET operation
Inside this Action method, the GetFiles method is called.
Inside the GetFiles method, the records from the tblFiles table are fetched using DataReader and generic list of FileModel class objects is populated.
Note: For details about reading Connection String from AppSettings.json, please refer my article, .Net Core: Read Connection String from AppSettings.json file.
 
Finally, the generic list of FileModel class objects is returned to the View.
 
Action method for handling POST operation for uploading Files
This Action method gets called when a File is selected and the Upload Button is clicked, and it gets the uploaded file in the IFormFile parameter.
Note: In case the IFormFile parameter is appearing NULL, then please refer the article, ASP.Net Core: IFormFile always returns NULL.
 
The uploaded file is converted to an Array of Bytes using MemoryStream class and finally, is inserted into the database table.
After successful insert of the File, the GetFiles method is called and the generic list of FileModel class objects is returned to the View.
 
Action method for sending Binary Data from Database to jQuery AJAX function
When the View Link inside the HTML Table (Grid) is clicked, then the ID of the particular file is sent to this Action method and using the File ID, the File’s binary data is fetched from the database.
Note: The following Action method performs File display and hence the return type is set to JsonResult.
 
Finally, JSON is returned back to the jQuery AJAX function.
public class HomeController : Controller
{
    private IConfiguration Configuration;
 
    public HomeController(IConfiguration _configuration)
    {
        Configuration = _configuration;
    }
    public IActionResult Index()
    {
        return View(this.GetFiles());
    }
 
    [HttpPost]
    public IActionResult Index(IFormFile postedFile)
    {
        string fileName = Path.GetFileName(postedFile.FileName);
        string contentType = postedFile.ContentType;
        using (MemoryStream ms = new MemoryStream())
        {
            postedFile.CopyTo(ms);
            string constr = this.Configuration.GetConnectionString("MyConn");
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "INSERT INTO tblFiles VALUES (@Name, @ContentType, @Data)";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", fileName);
                    cmd.Parameters.AddWithValue("@ContentType", contentType);
                    cmd.Parameters.AddWithValue("@Data", ms.ToArray());
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
 
        return View(this.GetFiles());
    }
 
    [HttpPost]
    public JsonResult GetWordDocument(int fileId)
    {
        byte[] bytes;
        string fileName, contentType;
        string constr = this.Configuration.GetConnectionString("MyConn");
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
                cmd.Parameters.AddWithValue("@Id", fileId);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["Data"];
                    contentType = sdr["ContentType"].ToString();
                    fileName = sdr["Name"].ToString();
                }
                con.Close();
            }
        }
 
        return Json(new { FileName = fileName, ContentType = contentType, Data = bytes });
    }
 
    private List<FileModel> GetFiles()
    {
        List<FileModel> files = new List<FileModel>();
        string constr = this.Configuration.GetConnectionString("MyConn");
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM tblFiles"))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        files.Add(new FileModel
                        {
                            Id = Convert.ToInt32(sdr["Id"]),
                            Name = sdr["Name"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }
        return files;
    }
}
 
 
View
Inside the View, in the very first line the FileModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
This Form consists of an HTML FileUpload and a Submit Button.
Uploading the File
When the Submit Button is clicked, the Index Action method for handling POST operation will be called.
 
Displaying the Word Files
For displaying the files, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the File records.
 
docx-preview.js JavaScript Implementation
First, the JavaScript files are inherited for the docx-preview.js JavaScript plugin.
When the View Anchor Link is clicked, the FileId is fetched from the rel attribute and then a jQuery AJAX call is made to the Controller’s Action Method.
Then inside the Success event handler, the Binary Data of the Word file is received in BASE64 string format.
The BASE64 string is converted into Byte Array using the Base64ToBytes JavaScript function and then it is converted into HTML5 File object.
Finally, the docx-preview.js library options are initialized and the Word file is rendered in the Container DIV using the renderAsync function.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model IEnumerable<Display_Word_Database_Core_MVC.Models.FileModel>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body { font-family: Arial; font-size: 10pt; }
        table { border: 1px solid #ccc; border-collapse: collapse; }
        table th { background-color: #F7F7F7; color: #333; font-weight: bold; }
        table th, table td { padding: 5px; border: 1px solid #ccc; }
    </style>
</head>
<body>
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
        <input type="file" name="postedFile" accept=".docx" />
        <input type="submit" id="btnUpload" value="Upload" />
    </form>
    <hr/>
    <table id="tblFiles" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:120px">File Name</th>
            <th></th>
        </tr>
        @foreach (var file in Model)
        {
            <tr>
                <td>@file.Name</td>
                <td><a class="view" href="javascript:;" rel='@file.Id'>View Word Doc</a></td>
            </tr>
        }
    </table>
    <hr/>
    <div id="word-container" class=""></div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
    <script src="~/Scripts/docx-preview.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id*=tblFiles] .view").click(function () {
                var fileId = $(this).attr("rel");
                $.ajax({
                    type: "POST",
                    url: "/Home/GetWordDocument",
                    data: { "fileId": fileId },
                    success: function (r) {
                        //Convert Base64 string to Byte Array.
                        var bytes = Base64ToBytes(r.Data);
 
                        //Convert BLOB to File object.
                        var doc = new File([bytes], r.ContentType);
 
                        //If Document not NULL, render it.
                        if (doc != null) {
                            //Set the Document options.
                            var docxOptions = Object.assign(docx.defaultOptions, {
                                useMathMLPolyfill: true
                            });
                            //Reference the Container DIV.
                            var container = document.querySelector("#word-container");
 
                            //Render the Word Document.
                            docx.renderAsync(doc, container, null, docxOptions);
                        }
                    }
                });
            });
        });
 
        function Base64ToBytes(base64) {
            var s = window.atob(base64);
            var bytes = new Uint8Array(s.length);
            for (var i = 0; i < s.length; i++) {
                bytes[i] = s.charCodeAt(i);
            }
            return bytes;
        };
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: Display Word files from Database in View
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads