相关文章推荐
精明的手套  ·  java ...·  1 年前    · 

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

This is where I insert the word docx into database

 <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 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>  
                        <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>`;  
            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>  
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 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>  
    <form id="form1" runat="server">  
        <asp:ScriptManager ID="script" runat="server"></asp:ScriptManager>  
            <div id="content" style="font-size: 10pt; width: 100%;">  
                <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" />  
                        </asp:Panel>  
    </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>  
 [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;  
											

Hi @Donald Symmons ,
The code you provided is a bit messy and incomplete. It's hard to reproduce your problem.
Did you get the base64 string right? I don't seem to see you using the Base64ToBytes(base64) method.
You can run a test to see if there is a problem with printworddocx.aspx.

I don't seem to see you using the Base64ToBytes(base64) method

Its working in another page without issue. But on the other page it shows a blank page.

The code you provided is a bit messy and incomplete

really? Which is not? people got different ways of writing to get one outcome

Seriously!? You dropped a bunch of code without explaining how the code works!

Anyway, there are a lot of errors. Fix the errors one at a time. Your code references a jQuery library that is not loaded and there is a 404 error loading a file. Fix theses errors!!!

I think, the problem is the PreviewWordDoc(file) function expects a file.Data property but the Web Method does not return a Data property. It returns a Name, image, and Contyp property.

Learn how to use the standard debuggers in Visual Studio and the browser's Dev Tools. It is very easy to check if file.Data has data by setting a break point and/or writing variable contents to the console; console.log(variable);. Plus the error tells you exactly where the error is located within the code. Usually, you can click the error which will take you directly to the line of code that caused the error.

Hi @AgaveJoe ,

Okay. I saw this tutorial online which enables word document to be uploaded onto a web page, then inserted into database. After inserting it redirects to another page. and the word document displays. The surprising thing is that it actually works on another web form I created, but does not work in this particular one

On the other page are you using response.d (like below) or response.image ?:

   success: function (response) {  
       var file = response.d;  
       PreviewWordDoc(file);  

The surprising thing is that it actually works on another web form I created, but does not work in this particular one

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 };  

Please debug your code.

From your comment

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 };

I made changes to the above line of code. Changed image to Data, and Contyp to ContentType.
You are too good
Thanks a million.

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 ?

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 };