Asp.net 预览图像功能导致文件上载控件重置

Asp.net 预览图像功能导致文件上载控件重置,asp.net,vb.net,image,file-upload,preview,Asp.net,Vb.net,Image,File Upload,Preview,“我的图像”上载的代码段: 'Read the file and convert it to Byte Array Dim filePath As String = FileUpload1.PostedFile.FileName Dim filename As String = Path.GetFileName(filePath) Dim ext As String = Path.GetExtension(filename) Dim contenttype As String = Str

“我的图像”上载的代码段:

'Read the file and convert it to Byte Array
 Dim filePath As String = FileUpload1.PostedFile.FileName
 Dim filename As String = Path.GetFileName(filePath)
 Dim ext As String = Path.GetExtension(filename)
 Dim contenttype As String = String.Empty

 'Set the contenttype based on File Extension
 Select Case ext
      Case ".jpg"
           contenttype = "image/jpg"
           Exit Select
      Case ".png"
           contenttype = "image/png"
           Exit Select
 End Select

If Not contenttype Is String.Empty Then

 Dim fs As Stream = FileUpload1.PostedFile.InputStream
 Dim br As New BinaryReader(fs)
 Dim bytes As Byte() = br.ReadBytes(fs.Length)

 'insert the file into database
 cmd.Parameters.Add("@imgName", SqlDbType.VarChar).Value = filename
 cmd.Parameters.Add("@contentType", SqlDbType.VarChar).Value = contenttype
 cmd.Parameters.Add("@data", SqlDbType.Binary).Value = bytes

Else

 cmd.Parameters.Add("@imgName", SqlDbType.VarChar).Value = DBNull.Value
 cmd.Parameters.Add("@contentType", SqlDbType.VarChar).Value = DBNull.Value
 cmd.Parameters.Add("@data", SqlDbType.Binary).Value = DBNull.Value

End If

con.Open()
cmd.ExecuteNonQuery()
con.Close()


预览图像:

Protected Sub preview_btn_Click(sender As Object, e As EventArgs) Handles preview_btn.Click
    Session("ImageBytes") = FileUpload1.FileBytes
    Image1.ImageUrl = "~/Handler1.ashx"

    preview_btn.BackColor = Drawing.Color.Lime
    preview_btn.ForeColor = Drawing.Color.White

    Image1.BorderColor = Drawing.Color.Lime
End Sub


Handler1.ashx

<%@ WebHandler Language="VB" Class="Handler1" %>

Imports System
Imports System.Web

Public Class Handler1 : Implements System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    If (context.Session("ImageBytes")) IsNot Nothing Then
        Dim image As Byte() = DirectCast(context.Session("ImageBytes"), Byte())
        context.Response.ContentType = "image/jpeg"
        context.Response.BinaryWrite(image)
    End If
End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
End Property

End Class

导入系统
导入系统.Web
公共类句柄1:实现System.Web.IHttpHandler、System.Web.SessionState.IRequiresessionState
Public Sub-ProcessRequest(ByVal上下文作为HttpContext)实现IHttpHandler.ProcessRequest
如果(context.Session(“ImageBytes”)不是空的,那么
Dim image As Byte()=DirectCast(context.Session(“ImageBytes”),Byte())
context.Response.ContentType=“image/jpeg”
context.Response.BinaryWrite(图像)
如果结束
端接头
公共只读属性IsReusable()作为布尔值实现IHttpHandler.IsReusable
得到
返回错误
结束
端属性
末级


预览图像可以工作,但每当我调用预览图像按钮时,
FileUpload
控件就会复位

因此,从
FileUpload
控件的角度来看,用户似乎一开始没有选择任何图像

我尝试先将
FileUpload1.PostedFile.FileName
的值存储在某个变量中,然后手动设置其值,但
FileUpload1.PostedFile.FileName
似乎是只读的,从安全角度看这是有意义的


因此,如何解决这个问题?

要快速解决问题,我将执行以下操作:

  • 预览-在会话中保存发布的文件。将Image1图像url设置为handler
  • 处理程序-从会话中获取发布的文件。将图像写入响应
  • 上传-检查文件上传1中是否存在文件,获取它。如果没有,就去拿吧 会议结束后。保存图像。会议结束
  • 以下是我将使用的代码:

    编辑:更改代码以修复较大(>50kb)图像的问题

    aspx.vb

    Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
        'Disabled DB operations for test
        'Read the file and convert it to Byte Array
        Dim filePath As String = String.Empty
        Dim filename As String = String.Empty
        Dim ext As String = String.Empty
        Dim contenttype As String = String.Empty
        Dim bytes As Byte()
    
        If FileUpload1.HasFile Then
            filePath = FileUpload1.PostedFile.FileName
        Else
            If (Session("MyFile") IsNot Nothing AndAlso Session("MyFileName") IsNot Nothing) Then
                filePath = Session("MyFileName").ToString()
                bytes = DirectCast(Session("MyFile"), Byte())
            End If
        End If
    
        filename = Path.GetFileName(filePath)
        ext = Path.GetExtension(filename)
    
        'Set the contenttype based on File Extension
        Select Case ext
            Case ".jpg"
                contenttype = "image/jpg"
                Exit Select
            Case ".png"
                contenttype = "image/png"
                Exit Select
        End Select
    
        If Not contenttype Is String.Empty Then
            If FileUpload1.HasFile Then
                Dim fs As Stream = FileUpload1.PostedFile.InputStream
                Dim br As New BinaryReader(fs)
                bytes = br.ReadBytes(fs.Length)
            End If
            'insert the file into database
            cmd.Parameters.Add("@imgName", SqlDbType.VarChar).Value = filename
            cmd.Parameters.Add("@contentType", SqlDbType.VarChar).Value = contenttype
            cmd.Parameters.Add("@data", SqlDbType.Binary).Value = bytes
    
        Else
    
            cmd.Parameters.Add("@imgName", SqlDbType.VarChar).Value = DBNull.Value
            cmd.Parameters.Add("@contentType", SqlDbType.VarChar).Value = DBNull.Value
            cmd.Parameters.Add("@data", SqlDbType.Binary).Value = DBNull.Value
    
        End If
    
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    
        'Cleanup
        Session("MyFile") = Nothing
        Session("MyFileName") = Nothing
    End Sub
    
    Protected Sub preview_btn_Click(sender As Object, e As EventArgs) Handles preview_btn.Click
        If FileUpload1.PostedFile IsNot Nothing Then
            Dim file As HttpPostedFile = FileUpload1.PostedFile
    
            Dim data As Byte() = New [Byte](file.ContentLength - 1) {}
            file.InputStream.Read(data, 0, file.ContentLength)
    
            Session("MyFile") = data
            Session("MyFileName") = FileUpload1.PostedFile.FileName
            Image1.ImageUrl = "~/Handler1.ashx"
    
            preview_btn.BackColor = Drawing.Color.Lime
            preview_btn.ForeColor = Drawing.Color.White
    
            Image1.BorderColor = Drawing.Color.Lime
        End If
    End Sub
    
    Handler1.ashx

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If (context.Session("MyFile")) IsNot Nothing Then
            Dim storedImage = TryCast(context.Session("MyFile"), Byte())
            If storedImage IsNot Nothing Then
                context.Response.ContentType = "image/jpeg"
                context.Response.BinaryWrite(storedImage)
            End If
        End If
    End Sub
    

    希望有帮助

    试用后,我得到一个
    系统。ObjectDisposedException未经用户代码处理
    无法访问已关闭的文件。
    图像上显示为Byte()=br.ReadBytes(fs.Length)
    第一次尝试预览时,我创建了两个新页面,并复制了
    预览\u btn\u单击
    代码和
    句柄1.ashx
    您发布的代码,但仍然遇到相同的问题。您可以下载测试项目并与您的进行比较。或者你可以给你的项目发电子邮件,让我看看。我想我可能发现了问题,但没有找到解决方案。我试着用不同的图像来测试它,有些作品,有些则不然。所有图像都是
    .jpg
    ,只有低于50KB的图像才有效。奇怪…@j_t_fusion-好的,我已经用较大图像的修复程序更新了源代码。还添加了指向我的测试项目的链接。