How to insert word file into database

Donald Symmons 2,856 Reputation points
2022-06-04T15:42:39.693+00:00

I have this code that display word file in html after uploading; but I tried to insert the file into database as byte and got an error as shown below208385-docx-error.png

This is the code I used. please forum, how can I achieve this task? I just want to insert the word file as byte into database. Thank you.
HTML

<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" />  
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>  
<script type="text/javascript" src="https://unpkg.com/core-js-bundle@3.3.2/minified.js"></script>  
<script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>  
<script type="text/javascript" src="https://volodymyrbaydalka.github.io/docxjs/dist/docx-preview.js"></script>  
<script type="text/javascript" src="https://volodymyrbaydalka.github.io/docxjs/demo/thumbnail.example.js"></script>  
<link rel="stylesheet" href="https://volodymyrbaydalka.github.io/docxjs/demo/thumbnail.example.css" />  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <div class="vh-100 d-flex flex-column">  
            <div class="hstack p-2 gap-2 bg-light">  
                <input id="files" type="file" runat="server" class="form-control" style="width: 50ch;" accept=".docx" />  
                <button id="loadButton" runat="server" type="button" class="btn btn-primary px-4">Load</button>  
                 <asp:Button ID="continue" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="#32657c" Font-Size="9pt" Text="QR code" OnClick="continue_Click" />  
            </div>  
            <div class="flex-grow-1 d-flex flex-row" style="height: 0;">  
                <details class="docx-thumbnails h-100">  
                    <summary></summary>  
                    <div id="thumbnails-container" class="docx-thumbnails-container"></div>  
                </details>  
                <div id="document-container" class="overflow-auto flex-grow-1 h-100"></div>  
            </div>  
        </div>  
    </div>  
    </form>  
     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>  
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>  
     <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>  
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>  
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.18/mammoth.browser.min.js"></script>  
    <script type="text/javascript">  
    let currentDocument = null;  
    const docxOptions = Object.assign(docx.defaultOptions, {  
        debug: true,  
        experimental: true,  
        useMathMLPolyfill: true  
    });  
   
    const container = document.querySelector("#document-container");  
   
    function renderDocx(file) {  
        currentDocument = file;  
        if (!currentDocument)  
            return;  
   
        docx.renderAsync(currentDocument, container, null, docxOptions)  
            .then((x) => {  
                renderThumbnails(container, document.querySelector("#thumbnails-container"));  
            });  
    }  
   
    document.querySelector("#loadButton").addEventListener("click", ev => {  
        renderDocx(document.getElementById("files").files[0]);  
    });  
   
    Object.keys(docxOptions).filter(key => !/className/i.test(key)).forEach(function (key) {  
        const listItem = document.createElement("li");  
        listItem.innerHTML = `  
    <div class="dropdown-item">  
        <div class="form-check">  
            <label class="form-check-name"><input type="checkbox" class="form-check-input" ${docxOptions[key] ? 'checked' : ''}> ${key}</label>  
        </div>  
    </div>`;  
   
        const checkInput = listItem.querySelector("input");  
   
        checkInput.addEventListener("click", (e) => {  
            docxOptions[key] = checkInput.checked;  
            renderDocx(currentDocument);  
        });  
    });  
   
    container.addEventListener("dragover", ev => ev.preventDefault());  
    container.addEventListener("drop", ev => {  
        ev.preventDefault();  
        renderDocx(ev.dataTransfer.files[0]);  
    });  
</script>  
</body>  
</html>  

C#

    protected void continue_Click(object sender, EventArgs e)  
    {  
            string filename = Path.GetFileName(files.PostedFile.FileName);  
            string contentType = files.PostedFile.ContentType;  
            using (Stream fs = files.PostedFile.InputStream)  
            {  
                using (BinaryReader br = new BinaryReader(fs))  
                {  
                    byte[] bytes = br.ReadBytes((Int32)fs.Length);  
                    using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"))  
                    {  
                        string query = "INSERT INTO tableinvoice(Name, ContentType, Data, CreatedDate)" +  
                    " VALUES(@Name, @ContentType, @Data, @CreatedDate); SELECT @@IDENTITY";  
                        using (SqlCommand cmd = new SqlCommand(query))  
                        {  
                            cmd.Connection = con;  
                            cmd.Parameters.AddWithValue("@Name", filename);  
                            cmd.Parameters.AddWithValue("@ContentType", contentType);  
                            cmd.Parameters.AddWithValue("@Data", bytes);  
                            cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);  
                            con.Open();  
                            object Invoice = cmd.ExecuteScalar();  
                            con.Close();  
                            Session["indocx"] = Invoice;  
                            Response.Redirect("Worddoc.aspx");  
                        }  
                    }  
                }  
        }  
    }  
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,249 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,223 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,471 Reputation points Microsoft Vendor
    2022-06-06T06:31:28.937+00:00

    Hi @Donald Symmons ,
    I tested your code and it works fine.
    I added organization and named based on the code you provided (I set <asp:TextBox ID="named" to test). Also the connection string is different, other code is exactly the same.
    How big is your Word file? I suggest you can create a new Word file for testing.
    Check if there are some associated table columns with unset values.
    208633-image.png
    208488-demo1.gif

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,366 Reputation points
    2022-06-04T16:59:41.41+00:00

    We would need to see the table definition to understand the overflow error.


  2. Bruce (SqlWork.com) 55,366 Reputation points
    2022-06-04T19:10:04.017+00:00

    your code does not match the error message.

    where is the :

    cmd. Parameters.AddWithValue ("@Organization", named.Text.Trim())