浏览后直接上传文件

时间:2016-12-19 14:28:06

标签: asp.net vb.net file-upload

我创建了一个简单的方法,可以在单击按钮时将文件上传到服务器。这种方法在按钮点击时非常有效,但是当用户从他的计算机中选择文件时,我需要直接自动上传。有关如何制作它的任何想法? 这是我的asp代码:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate >
       <asp:FileUpload ID="FileUpload1" runat="server" />
       <br/>
       <asp:Label ID="Label1" runat="server"></asp:Label>
       <br/>
       <asp:Button ID="Button1" runat="server" Text="Upload" />
    </ContentTemplate>
    <Triggers>
       <asp:PostBackTrigger ControlID="Button1" />
    </Triggers>
</asp:UpdatePanel>

以下是背后的代码:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim path As String = Server.MapPath("~/UploadedImages/")
        Dim fileOK As Boolean = False
        If FileUpload1.HasFile Then
            Dim fileExtension As String
            fileExtension = System.IO.Path. _
                GetExtension(FileUpload1.FileName).ToLower()
            Dim allowedExtensions As String() = _
                {".jpg", ".jpeg", ".png", ".gif"}
            For i As Integer = 0 To allowedExtensions.Length - 1
                If fileExtension = allowedExtensions(i) Then
                    fileOK = True
                End If
            Next
            If fileOK Then
                Try
                    FileUpload1.PostedFile.SaveAs(path & _
                         FileUpload1.FileName)
                    Label1.Text = "File uploaded!"
                Catch ex As Exception
                    Label1.Text = "File could not be uploaded."
                End Try
            Else
                Label1.Text = "Cannot accept files of this type."
            End If
        End If
    End Sub

1 个答案:

答案 0 :(得分:0)

首先,将一个虚拟LinkBut​​ton添加到aspx页面。将文本保留为空,以便用户看不到它,但确实存在于HTML中。

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>

然后在代码后面的FileUpload控件中添加一个javascript侦听器,当发生更改时,它将执行LinkBut​​ton1的PostBack。

protected void Page_Load(object sender, EventArgs e)
{
    FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
}

protected void LinkButton1_Click(object sender, EventArgs e)
{
    //handle the file upload
}

VB

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    FileUpload1.Attributes.Add("onchange", ("__doPostBack('"  _
                    + (LinkButton1.UniqueID + "','')")))
End Sub

Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs)
    'handle the file upload
End Sub