【问题标题】:I have written a vb.net code to display image in the image control but not able to display the image我编写了一个 vb.net 代码来在图像控件中显示图像但无法显示图像
【发布时间】:2022-01-13 11:54:49
【问题描述】:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim con As New SqlConnection
    Dim img As New Image
    con.ConnectionString = ("Initial Catalog=test; Data Source=LAPTOP-DJ6MPGR2\ROOT123;User ID=SA;Password=root;Integrated Security=False;MultipleActiveResultSets=True")
    con.Open()
    Dim cmd As New SqlCommand("select  image from Images ", con)
    cmd.Connection = con
    Dim dr As SqlDataReader = cmd.ExecuteReader()
    If (dr.HasRows) Then
        While (dr.Read)
            Dim bytes As Byte() = DirectCast(dr("image"), Byte())
            Image1.ImageUrl = Convert.ToBase64String(bytes)
        End While
    End If

    con.Close()
End Sub

【问题讨论】:

  • base64 图像 URL 包含的不仅仅是 base64 字符串本身...看看stackoverflow.com/questions/8499633/…
  • 另外,在con.Close()之后需要一个额外的命令:con.Dispose()
  • 请注意,select image from Images 将选择 all 图像的值,而While (dr.Read) 将遍历所有这些图像,因此 Image1.ImageUrl 属性最终将是只有最后一个值。要么在选择中添加一个合适的WHERE 子句,以便只返回一个结果,或者你可以使用SELECT TOP 1 [image] FROM [Images] 将其限制为一个结果。
  • 使用Using 块。将Dim con As New SqlConnection 替换为Using con As New SqlConnection() 并将con.Close() 替换为End UsingDim cmd ... 也是如此。然后你就不需要调用 Dispose
  • 我承认我真的很基础,因为我不太确定你的数据库中有什么。 Image1.ImageUrl 是图像的路径,而不是图像本身

标签: html asp.net vb.net image base64url


【解决方案1】:

下面将展示如何将图像上传到 SQL Server 数据库,以及如何从数据库中检索图像并将其显示在 ASP.NET 网页上。

在数据库中创建表

Create Table Images(Id int IDENTITY(1, 1) Not null,
Image varbinary(max),
Constraint PK_Images_Id PRIMARY KEY(Id));

确实不应该使用 SQL Server 'sa' 用户来访问数据库,因为这会产生安全问题。而是为您的应用程序创建一个用户。

创建数据库用户

  • 打开 Microsoft SQL Server Management Studio
  • 展开安全
  • 右键单击登录
  • 选择新登录
  • 选择 SQL Server 身份验证
  • 登录名:(例如:appUser)
  • 输入您想要的密码
  • 取消选中“用户下次登录时必须更改密码”
  • 选择所需的默认数据库(例如:testDR)
  • 点击确定

将用户添加到数据库

  • 打开 Microsoft SQL Server Management Studio
  • 扩展数据库
  • 扩展(例如:testDR)
  • 展开安全
  • 右键单击用户
  • 选择新用户...
  • 输入所需的用户名(例如:appUser)
  • 对于“登录名”,请单击...
  • 点击浏览
  • 选择所需的用户(例如:appUser)
  • 点击确定
  • 点击确定
  • 将“默认架构”留空。
  • 点击确定

授予用户对表的权限

  • 打开 Microsoft SQL Server Management Studio
  • 扩展数据库
  • 扩展(例如:testDR)
  • 展开表格
  • 右键单击(例如:dbo.Images)
  • 选择属性
  • 在“选择页面”下,点击权限
  • 点击搜索
  • 点击浏览
  • 检查所需用户(例如:appUser)
  • 点击确定
  • 点击确定
  • Grant 下,检查以下内容:删除、插入、选择、更新
  • 点击确定

注意:“With Grant”允许用户将权限授予另一个用户。

VS 2019

创建一个新项目

  • 打开 Visual Studio

  • 点击无代码继续

  • 点击文件

  • 选择新建

  • 选择项目

  • 选择以下选项:

  • 点击下一步

  • 选择以下:

  • 点击下一步

  • 输入所需的项目名称

  • 点击创建

  • 选择以下选项:

  • 高级下,取消选中Configure for HTTPS

  • 点击创建

打开解决方案资源管理器

  • 在VS菜单中,点击查看
  • 选择解决方案资源管理器

添加WebForm(名称:default.aspx)

  • 在解决方案资源管理器中,右键单击
  • 选择添加
  • 选择新项目...
  • 选择Web 表单(名称:default.aspx)
  • 点击添加

添加 WebForm(名称:DisplayImage.aspx)

  • 在解决方案资源管理器中,右键单击
  • 选择添加
  • 选择新项目...
  • 选择Web 表单(名称:DisplayImage.aspx)
  • 点击添加

将连接字符串添加到 Web.config

  • 在解决方案资源管理器中,双击 Web.config

在下面的代码中,根据您的环境修改<connectionStrings>...</connectionStrings> 中的代码(即:服务器、数据库名称、用户名、密码)。

Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="testDRConnection" connectionString="Server=.\SQLExpress;Database=testDR;User Id=appUser;Password=myAppPassword;" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

在“default.aspx”中,我们将添加将文件上传到数据库的功能。上传完成后,我们将使用“Display.aspx”来显示最后上传的图片。

在解决方案资源管理器中,双击 default.aspx

default.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="DatabaseGetImage.UploadImage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="frmDefault" runat="server">
        <div>
            <asp:Label ID="LabelFileUpload" for="FileUpload1" runat="server" Text="Label">Upload a File</asp:Label>
            <p />

            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="ButtonUploadFile" runat="server" Text="Upload" OnClick="ButtonUploadFile_Click" />
            <p />

            <asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
        </div>
    </form> 
</body>
</html>

以下是将图像上传到数据库的代码。

在解决方案资源管理器中,右键单击 default.aspx。选择查看代码

default.aspx.vb

Imports System.Configuration
Imports System.Data.SqlClient
Public Class UploadImage
    Inherits System.Web.UI.Page

    'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Function UploadImage(imageBytes As Byte()) As Integer
        Dim rowsAffected As Integer = 0
        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
        Dim sqlText As String = "INSERT INTO Images(Image) VALUES(@img);"

        Using con As SqlConnection = New SqlConnection(connectionStr)
            'open
            con.Open()

            Using cmd As SqlCommand = New SqlCommand(sqlText, con)
                'size = -1 is needed to exceed 8000 bytes; it maps to varbinary(max)
                cmd.Parameters.Add("@img", SqlDbType.VarBinary, -1).Value = imageBytes

                'execute
                rowsAffected = cmd.ExecuteNonQuery()
            End Using
        End Using

        Return rowsAffected
    End Function

    Protected Sub ButtonUploadFile_Click(sender As Object, e As EventArgs)
        If FileUpload1.HasFile() Then
            LblMsg.Text = "Filename: " & FileUpload1.FileName & " File bytes: " & FileUpload1.FileBytes.Length

            'upload image to database
            Dim rowsAffected As Integer = UploadImage(DirectCast(FileUpload1.FileBytes, Byte()))

            Response.Redirect("DisplayImage.aspx")
        End If
    End Sub
End Class

接下来,我们将修改“DisplayImage.aspx”,使其显示图像。

在解决方案资源管理器中,双击 DisplayImage.aspx

DisplayImage.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="DisplayImage.aspx.vb" Inherits="DatabaseGetImage.displayImage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<div>
    <asp:Image ID="Image1" runat="server" ></asp:Image>
    <p />

    <asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
    </div>
</body>
</html>

下面的代码从数据库中检索图像并显示它。

在解决方案资源管理器中,右键单击 DisplayImage.aspx。选择查看代码

DisplayImage.aspx.vb

Imports System.Configuration
Imports System.Data.SqlClient
Public Class displayImage
    Inherits System.Web.UI.Page

    'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim imagesBytes As Byte() = GetImage(id:=1) 'get image with id = 1

        If imagesBytes IsNot Nothing Then
            'LblMsg.Text = "Base64 String: " & Convert.ToBase64String(imagesBytes)

            Image1.ImageUrl = "data:image/jpeg;base64," & Convert.ToBase64String(imagesBytes)
        End If
    End Sub

    Protected Function GetImage(id As Integer) As Byte()
        Dim imageBytes As Byte() = Nothing
        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
        Dim sqlText As String = "SELECT * from Images where Id = (SELECT max(Id) from Images)"

        Try
            Using con As SqlConnection = New SqlConnection(connectionStr)
                con.Open() 'open

                Using cmd As SqlCommand = New SqlCommand(sqlText, con)
                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id

                    Using dr As SqlDataReader = cmd.ExecuteReader()
                        If dr.HasRows Then
                            While dr.Read()
                                imageBytes = DirectCast(dr("image"), Byte())
                            End While
                        End If
                    End Using
                End Using
            End Using
        Catch ex As SqlException
            'ToDo: add desired code
            LblMsg.Text = "Error: " & ex.Message
            'Throw
        Catch ex As Exception
            'ToDo: add desired code
            LblMsg.Text = "Error: " & ex.Message
            'Throw
        End Try

        Return imageBytes
    End Function

End Class

资源

【讨论】:

  • 干杯,到目前为止效果很好。如何在同一页面上显示数据库中的多个图像?如何在运行时动态添加图片?
  • 以下可能会有所帮助:stackoverflow.com/questions/70317980/…
猜你喜欢
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 2016-06-28
  • 2017-02-18
相关资源
最近更新 更多