为HtmlInputFile自动加上multipart/form-data编码类型

类别:.NET开发 点击:0 评论:0 推荐:

Imports System.Web.UI

Imports System.ComponentModel

Public Class UpLoadFile

    Inherits System.Web.UI.WebControls.WebControl

    '设置将窗体的数据发送到服务器时浏览器使用的编码类型

    'multipart/form-data 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。

    Protected Overridable Sub EnsureEncType()

        Dim parent As System.Web.UI.Control = Me.Parent

        While Not (parent Is Nothing) AndAlso Not (parent.GetType Is GetType(System.Web.UI.HtmlControls.HtmlForm)) AndAlso Not (parent.GetType Is GetType(System.Web.UI.Page))

            parent = parent.Parent

        End While

        Dim myForm As System.Web.UI.HtmlControls.HtmlForm = parent

        If Not (parent Is Nothing) Then

            myForm.Enctype = "multipart/form-data"

        End If

    End Sub

    '重写TagKey属性.编写 HTML 标记为input

    Protected Overloads Overrides ReadOnly Property TagKey() As System.Web.UI.HtmlTextWriterTag

        Get

            Return HtmlTextWriterTag.Input

        End Get

    End Property

    '重写自定义服务器控件中的 OnPreRender 方法,

    '当从 ASP.NET 页请求自定义控件时,在页处理的 PreRender 阶段(当服务器控件将要呈现给其包含的 Page 对象时发生)会调用 OnPreRender 方法

    Protected Overloads Overrides Sub OnPreRender(ByVal e As System.EventArgs)

        MyBase.OnPreRender(e)

        If Not (Me.Page Is Nothing) Then '如果页面由此控件实例

            Me.EnsureEncType()

        End If

    End Sub

 

    Protected Overloads Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

        If Not (Me.Page Is Nothing) Then

            Me.Page.VerifyRenderingInServerForm(Me) '确认在运行时为指定的 ASP.NET 服务器控件包含在 HtmlForm 服务器控件 (<form runat="server">) 中

        End If

        MyBase.AddAttributesToRender(writer)

        MyBase.Render(writer)

    End Sub

    Protected Overloads Overrides Sub AddAttributesToRender(ByVal writer As System.Web.UI.HtmlTextWriter)

        MyBase.AddAttributesToRender(writer)

        '输出html--file控件

        writer.AddAttribute(HtmlTextWriterAttribute.Type, "file")

        writer.AddAttribute(HtmlTextWriterAttribute.Name, Me.UniqueID)

    End Sub

End Class

 

本文地址:http://com.8s8s.com/it/it45196.htm