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
uj5u.com熱心網友回復:
下面將展示如何將影像上傳到 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 管理作業室
- 展開安全
- 右鍵單擊登錄
- 選擇新登錄
- 選擇SQL Server 身份驗證
- 登錄名:<所需的登錄名>(例如:appUser)
- 輸入您想要的密碼
- 取消選中“用戶必須在下次登錄時更改密碼”
- 選擇所需的默認資料庫(例如:testDR)
- 單擊確定
將用戶添加到資料庫
- 打開Microsoft SQL Server 管理作業室
- 擴展資料庫
- 展開 <所需資料庫>(例如:testDR)
- 展開安全
- 右鍵單擊用戶
- 選擇新用戶...
- 輸入所需的用戶名(例如:appUser)
- 對于“登錄名”,單擊
... - 點擊瀏覽
- 選擇所需的用戶(例如:appUser)
- 單擊確定
- 單擊確定
- 將“默認架構”留空。
- 單擊確定
授予用戶對表的權限
- 打開Microsoft SQL Server 管理作業室
- 擴展資料庫
- 展開 <所需資料庫>(例如:testDR)
- 展開表格
- 右鍵單擊 <所需表>(例如:dbo.Images)
- 選擇屬性
- 在“選擇頁面”下,單擊權限
- 點擊搜索
- 點擊瀏覽
- 檢查所需的用戶(例如:appUser)
- 單擊確定
- 單擊確定
- 在Grant 下,檢查以下內容:洗掉、插入、選擇、更新
- 單擊確定
注意:“With Grant”允許用戶將權限授予另一個用戶。
VS 2019:
創建一個新專案
打開 Visual Studio
點擊繼續,無需代碼
單擊檔案
選擇新建
選擇專案
選擇以下內容:

單擊下一步
選擇以下內容:

單擊下一步
輸入所需的專案名稱
點擊創建
選擇以下內容:

在Advanced 下,取消選中Configure for HTTPS
點擊創建
打開解決方案資源管理器
- 在 VS 選單中,單擊查看
- Select Solution Explorer
Add WebForm (name: default.aspx)
- In Solution Explorer, right-click <project name>
- Select Add
- Select New Item...
- Select Web Form (name: default.aspx)
- Click Add
Add WebForm (name: DisplayImage.aspx)
- In Solution Explorer, right-click <project name>
- Select Add
- Select New Item...
- Select Web Form (name: DisplayImage.aspx)
- Click Add
Add connection string to Web.config
- In Solution Explorer, double-click Web.config
In code below, modify the code within <connectionStrings>...</connectionStrings> for your environment (ie: server, database name, user name, password).
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>
In "default.aspx" we'll add the ability to upload a file to the database. When the upload is complete, we'll use "Display.aspx" to display the last uploaded image.
In Solution Explorer, double-click 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>
Below is the code that uploads an image to the database.
In Solution Explorer, right-click default.aspx. Select View Code
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
Next, we'll modify "DisplayImage.aspx" so that it will display an image.
In Solution Explorer, double-click 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>
The code below retrieves an image from the database and displays it.
In Solution Explorer, right-click DisplayImage.aspx. Select View Code
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
資源:
- 在 Web.config 中存盤連接字串
- SQL Server 連接字串
- 如何在 HTML 中顯示 Base64 影像
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/381467.html
上一篇:如何將位元組保存為影像?
下一篇:迭代陣列并替換值
