Watsyyy
Watsyyy

Reputation: 125

Getting error retrieving sql image from c# application

I'm getting an error when trying to load and display a table of images:

data:image/jpg;base64,U3lzdGVtLkJ5dGVbXQ== ' cannot load image because of an error'

My SQL DB has a FileName(nvarhcar) Content(image) and ContentType (nvarchar)

Hopefully someone can help me learn why the image is not displaying. Thanks

Update c# to load image

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["User"] == null)
                Response.Redirect("../Login.aspx");

            sqlcon.Open();
            SqlCommand cmd = sqlcon.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM BluePrints";

            cmd.ExecuteNonQuery();


            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            gvImages.DataSource = dt;
            gvImages.DataBind();

            sqlcon.Close();
        }

        protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView dr = (DataRowView)e.Row.DataItem;
                string imageUrl = "data:image/jpg;base64," + 
                Convert.ToBase64String((byte[])dr["Content"]);
                (e.Row.FindControl("Image1") as Image).ImageUrl = imageUrl;
            }
        }
    }
}
  <asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" Height="192px" Width="915px">
    <Columns>
      <asp:BoundField DataField="ID" HeaderText="ID" />
      <asp:BoundField DataField="FileName" HeaderText="Name" />
      <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
          <asp:Image ID="Image1" runat="server" />
        </ItemTemplate>
      </asp:TemplateField>
    </Columns>
  </asp:GridView>
  <div id="dialog" style="display: none">
  </div>
  <br />
  <br />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
  </script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/start/jquery-ui.css" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery- 
       ui.min.js"></script>
  <script type="text/javascript">
    $(function() {
      $("#dialog").dialog({
        autoOpen: false,
        modal: true,
        height: 600,
        width: 600,
        title: "Zoomed Image"
      });
      $("[id*=gvImages] img").click(function() {
        $('#dialog').html('');
        $('#dialog').append($(this).clone());
        $('#dialog').dialog('open');
      });
    });
  </script>
</asp:Content>

Insert code

protected void UploadButton_Click(object sender, EventArgs e)
    {

        FileInfo fi = new FileInfo(FileUploadControl.FileName);
        byte[] documentContent = FileUploadControl.FileBytes;

        string name = fi.Name;

        if (FileUploadControl.HasFile)
        {
            try
            {
                if (FileUploadControl.PostedFile.ContentType == "image/jpeg")
                {
                    if (FileUploadControl.PostedFile.ContentLength < 102400)
                    {

                        StatusLabel.Text = "Upload status: File uploaded!";

                        using (SqlConnection sqlcon = new SqlConnection(con))
                        {

                            sqlcon.Open();
                            SqlCommand cmd = sqlcon.CreateCommand();
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = "INSERT INTO BluePrints (ID_Dev, PlotID, FileName, Content) VALUES  (' " + DropDownList1.SelectedValue + " ', '" + DropDownList2.SelectedValue + "', '" + name + "', '" + documentContent + "')";

                            cmd.ExecuteNonQuery();
                        }
                    }

                    else
                        StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
                }
                else
                    StatusLabel.Text = "Upload status: Only JPEG files are accepted!";

            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }

        }

Upvotes: 0

Views: 145

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

Problem is that U3lzdGVtLkJ5dGVbXQ== decoded is System.Byte[] rather than anything that should be an image.

In other words, your code that displays the data is possibly fine. Instead, your data in the database is invalid. It should be actual byte array rather than a string that says it's a byte array.

Upvotes: 1

Related Questions