Uncaught DOMException: Failed to execute 'atob' on 'window' The string to be decoded is not correctly encoded

Donald Symmons 3,066 Reputation points
2022-12-29T05:21:40.647+00:00

Hello forum,

I created a situation where users can upload word document on a webpage, convert it into bytes and insert into database table; and it's working. But then after inserting into database table, it should redirect to another page to show that same document that was being inserted, but when it redirects I get a blank page. When I checked my browser console I saw this error.
What surprises me most is that, I created 2 pages to execute this function, and it is working on one page and not on another page ( the two pages serves two purposes though)

Here is what I mean
274705-error-with-docx.png

This is where I insert the word docx into database

HTML

 <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; font-size: 11pt;" accept=".docx" />  
                                <button id="loadButton" runat="server" type="button" class="btn btn-primary px-4" style="font-size: 10pt; background: #0b2436;">Load</button>  
                            </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>  
                        <asp:Button ID="buttonmail" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="#32657c" Font-Size="9pt" Text="Proceed" OnClick="buttonmail_Click" />  
  
 <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>  

C#

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 TableDocx(email, Name, Contyp, image, CreatedBy, CreatedDate)" +  
                    " VALUES(@email, @Name, @Contyp, @image, @CreatedBy, @CreatedDate); SELECT @@IDENTITY";  
                        using (SqlCommand cmd = new SqlCommand(query))  
                        {  
                            cmd.Connection = con;  
                            cmd.Parameters.AddWithValue("@email", user.Text.Trim());  
                            cmd.Parameters.AddWithValue("@Name", filename);  
                            cmd.Parameters.AddWithValue("@Contyp", contentType);  
                            cmd.Parameters.AddWithValue("@image", bytes);  
                            cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.Trim());  
                            cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);  
                            con.Open();  
                            object DocxID = cmd.ExecuteScalar();  
                            con.Close();  
                            Session["PaperRecpt"] = DocxID;  
                            Response.Redirect("printworddocx.aspx?reference=" + DocxID);  
                        }  
                    }  
                }  
            }  

Then here it should show the document inserted (I used a Web Method)

HTML

<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <meta charset="utf-8" />  
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />  
  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />  
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" intergrity="sha384-AYmEC3Yw5cVb3ZcuHt0A9w35dYTsvhLPVnYs9eStHfGJv0vKxVfELGroGkvsg+p" crossorigin="anonymous" />  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" />  
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous" />  
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css" />  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
    <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://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>  
    <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" />  
    <link href="css/bootstrap.min.css" rel="stylesheet" media="all" />  
    <link href="css/bootstrap.css" rel="stylesheet" media="all" />  
    <title></title>  
    <style type="text/css">  
        #page {  
            align-content: center;  
            text-align: center;  
        }  
  
        .contentt {  
            height: 100%;  
            margin-bottom: 18px;  
            overflow: hidden;  
            padding-bottom: 56.25%; /* 16/9 ratio */  
            padding-top: 30px; /* IE6 workaround*/  
            position: relative;  
            width: auto;  
        }  
  
        .print {  
            margin: 0 auto;  
        }  
 
        .contentt Literal,  
        .contentt object,  
        .contentt embed .contentt ltEmbed {  
            height: 100% !important;  
            left: 0;  
            position: absolute;  
            top: 0;  
            width: 100% !important;  
        }  
  
        #word-container {  
            height: auto;  
            width: auto;  
        }  
    </style>  
</head>  
<body>  
    <form id="form1" runat="server">  
        <asp:ScriptManager ID="script" runat="server"></asp:ScriptManager>  
            <div id="content" style="font-size: 10pt; width: 100%;">  
                <hr />  
                <asp:Label ID="labelid" runat="server" Text="uid"></asp:Label><asp:Label ID="createby" runat="server" Text="createby"></asp:Label><asp:Label ID="role" runat="server" Text="role"></asp:Label>  
                <div class="container" id="centered" style="margin: 0 auto; padding: 5px; font-family: Nunito;">  
                    <div class="form-horizontal">  
                        <asp:Button ID="btnPrinnt" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="#32657c" Font-Size="10pt" Text="Download Docx" />  
                        <asp:Panel ID="printpanel" runat="server">  
                            <div class="contentt">  
                                <div id="word-container"></div>  
                                <asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="85px" />  
                            </div>  
                        </asp:Panel>  
                    </div>  
                </div>  
                <br />  
            </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://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script>  
     <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 type="text/javascript" src="https://volodymyrbaydalka.github.io/docxjs/dist/docx-preview.js"></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 src="js/bootstrap.min.js"></script>  
       <script type="text/javascript">  
                    $(function () {  
                        $.ajax({  
                            type: "POST",  
                            url: "printworddocx.aspx/GetFile",  
                            data: "{}",  
                            contentType: "application/json; charset=utf-8",  
                            dataType: "json",  
                            success: function (response) {  
                                var file = response.d;  
                                PreviewWordDoc(file);  
                            },  
                            failure: function (response) {  
                                alert(response.responseText);  
                            },  
                            error: function (response) {  
                                alert(response.responseText);  
                            }  
                        });  
                    });  
  
                    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;  
                    };  
  
                    function PreviewWordDoc(file) {  
                        //Convert Base64 to Byte Array.  
                        var bytes = Base64ToBytes(file.Data);  
  
                        //Convert Byte Array to File object.  
                        var doc = new File([bytes], file.Name);  
  
                        //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);  
                    }  
    </script>  
</body>  
</html>  

C#

 [WebMethod(EnableSession = true)]  
    public static object GetFile()  
    {  
        string fileName = string.Empty;  
        byte[] bytes = null;  
        string type = string.Empty;  
        using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True"))  
        {  
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM TableDocx WHERE Id = @Id", con))  
            {  
                cmd.Parameters.AddWithValue("@Id", HttpContext.Current.Session["PaperRecpt"]);  
                con.Open();  
                using (SqlDataReader dr = cmd.ExecuteReader())  
                {  
                    if (dr.Read())  
                    {  
                        fileName = dr["Name"].ToString();  
                        bytes = (byte[])dr["image"];  
                        type = dr["Contyp"].ToString();  
                    }  
                }  
                con.Close();  
            }  
        }  
        return new { Name = fileName, image= Convert.ToBase64String(bytes), Contyp = type };  
    }  

Namespace

using System;  
using System.Data;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Data.SqlClient;  
using System.IO;  
using iTextSharp.text.pdf;  
using MessagingToolkit.QRCode.Codec;  
using System.Drawing.Imaging;  
using System.Drawing;  
using System.Web.Services;  
Developer technologies | ASP.NET | Other
Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Donald Symmons 3,066 Reputation points
    2022-12-30T08:30:48.607+00:00

    Hi @AgaveJoe ,

    I assume the other page does not have the same bug. The code is looking for a response that has a "Data" property. The Web Method does not return a "Data" property. The Web Method returns an anonymous type that contains; Name, image, and Contyp.

    return new { Name = fileName, image= Convert.ToBase64String(bytes), Contyp = type };

    On the other page, this is how the WebMethod returns type that contains Name, Data and Contentype

     return new { Name = fileName, Data = Convert.ToBase64String(bytes), ContentType = type };  
    

    I actually did not want to have the same table columns in two tables, that's why I changed the column names.
    Like in bytes (I changed the column name "Data" to "image"), and changed the type (ContentType to Contyp)

    Please debug your code.

    I will do that.
    But using specific names, could it have effect over some functions or events ?

    0 comments No comments

  2. Donald Symmons 3,066 Reputation points
    2023-01-10T08:26:16.73+00:00

    The error has been corrected. I had to change the data type in my table. For the image data (in bytes), I changed the column name from image to Data and from Contyp to ContentType.

    Then I used this value return

     return new { Name = fileName, Data = Convert.ToBase64String(bytes), ContentType = type };
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.