【发布时间】:2011-01-10 02:38:07
【问题描述】:
有什么方法可以用ASP.NET 和VB 上传图片吗?
我需要ASP.NET 一侧的“上传”按钮。
SQL server 2008 的表中已经有一个图像字段。
有什么办法可以做到吗?
【问题讨论】:
标签: asp.net vb.net image upload
有什么方法可以用ASP.NET 和VB 上传图片吗?
我需要ASP.NET 一侧的“上传”按钮。
SQL server 2008 的表中已经有一个图像字段。
有什么办法可以做到吗?
【问题讨论】:
标签: asp.net vb.net image upload
fileupload 控件:<asp:FileUpload runat="server" id="FileUpload1" />
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim bldgIDNum As Int32 = FormView_Building.SelectedValue
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
Dim imageSize As Byte() = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}
Dim uploadedImage__1 As HttpPostedFile = FileUpload1.PostedFile
uploadedImage__1.InputStream.Read(imageSize, 0, CInt(FileUpload1.PostedFile.ContentLength))
' Create SQL Connection
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Table (PrimaryKey,ImageData) VALUES (@PrimaryKey,@ImageData)"
cmd.CommandType = CommandType.Text
cmd.Connection = con
Dim PrimaryKey As New SqlParameter("@PrimaryKey", SqlDbType.Int, 32)
PrimaryKey.Value = (however you want to get it)
Dim UploadedImage__2 As New SqlParameter("@ImageData", SqlDbType.Image, imageSize.Length)
UploadedImage__2.Value = imageSize
cmd.Parameters.Add(UploadedImage__2)
con.Open()
Dim result As Integer = cmd.ExecuteNonQuery()
con.Close()
If result > 0 Then
lblMessage.Text = "File Uploaded"
End If
End If
ListView_BldgImages.DataBind()
End Sub
数据库列ImageData应该是varbinary(max)
使用以下内容创建一个名为 Handler_Image.ashx 的处理程序:
Imports System
Imports System.Web
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Handler_Image : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select ImageData from Table where PrimaryKey =@PrimaryKey"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ID As New SqlParameter("@PrimaryKey", System.Data.SqlDbType.Int)
ID.Value = context.Request.QueryString("PrimaryKey")
cmd.Parameters.Add(ID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("ImageData"), Byte()))
dReader.Close()
con.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
使用具有以下属性的图像控件显示图像:
ImageUrl='<%# "Handler_Image.ashx?PrimaryKey=" & Eval("PrimaryKey")%>'
替换connectionstring、表名和主键以适合您的应用程序
【讨论】: