下面将展示如何将图像上传到 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:
创建一个新项目
打开解决方案资源管理器
添加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=\"Web\" /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
资源: