如何解决为什么无法将图像保存在数据库中
我正在为系统使用VB.NET和SQL Server。将图像保存到数据库时出现问题。我需要在同一页面上保存和检索图像,但出现错误:
无法将System.DBNull强制转换为系统字节。
我已经尝试了几种编码来修复我的编码,但是没有用。
用于检索图像的代码。
Dim id As String = txtImages.Text.Trim() 'txtImages is textbox name
Image1.Visible = id <> ""
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id
='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the
serch textbox
If dt.Rows.Count > 0 Then
Dim bytes As Byte() = TryCast(dt.Rows(0)("ImagePic"),Byte())
Dim base64String As String = Convert.ToBase64String(bytes,bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image
in db the message will displayed
End If
End If
End Sub
保存图像的代码
Dim fileName As String = String.Empty
Dim filePath As String = String.Empty
Dim getPath As String = String.Empty
Dim pathToStore As String = String.Empty
Dim bytes As [Byte]()
Dim fs As FileStreamenter code here
Dim br As BinaryReader
Dim cmd As New SqlCommand("Updateonlyimage_Sp3",cs) ' SQL command for this page is inside SQL Server I declare it as Insertapprovalcustom_Sp2"
cmd.CommandType = CommandType.StoredProcedure
Try
If FileUpload1.HasFile Then
fileName = FileUpload1.FileName
filePath = Server.MapPath("HSCODE/" & Convert.ToString(System.Guid.NewGuid()) & fileName)
'path to doucument inside approval_pdf file
FileUpload1.SaveAs(filePath)
cmd.Parameters.AddWithValue("@id",Request.QueryString("id"))
cmd.Parameters.AddWithValue("@ImagePicName",fileName)
Dim getPos As Integer = filePath.LastIndexOf("\")
Dim len As Integer = filePath.Length()
getPath = filePath.Substring(getPos,len - getPos)
pathToStore = getPath.Remove(0,1)
cmd.Parameters.AddWithValue("@ImagePicPath",pathToStore)
fs = New FileStream(filePath,FileMode.Open,FileAccess.Read)
br = New BinaryReader(fs)
bytes = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
cmd.Parameters.AddWithValue("@ImagePic",bytes)
cmd.Parameters.AddWithValue("@ContentType",FileUpload1.PostedFile.ContentType)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。