在文件上传时显示的简单消息

时间:2012-05-16 13:15:52

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

我一直致力于ASP.NET网站中的文件上传部分。

使用以下代码,我可以让用户根据RegularExpressionValidator中设置的正则表达式上传文档。我很高兴这样做有效。

我现在想要完成的是一条消息,表明该文件已成功上传。我不确定如何完成此操作,但希望将其添加到名为“fileuploaded”的Label

以下是.aspx页面的代码:

<table width = "60%">
  <tr>
    <td>Modes of Operation:</td>
    <td>
       <asp:FileUpload ID="FileUpload1" runat="server" />
    </td>
    <td>
       <asp:Button ID="buttonUpload" runat="server" Text="Upload" ValidationGroup="FileUpload" />
    </td>
  </tr>
  <tr>
    <td colspan="3">
       <asp:RequiredFieldValidator ID="FilenameRFValidator" runat="server" 
            ControlToValidate="FileUpload1" Display="Dynamic" 
            ErrorMessage="RequiredFieldValidator" ValidationGroup="FileUpload"> 
            * Please select a file to upload...
       </asp:RequiredFieldValidator></td>
   </tr>
   <tr>
     <td colspan="3">
        <asp:RegularExpressionValidator ID="FilenameRegExValidator" runat="server" 
             ControlToValidate="FileUpload1" Display="Dynamic" 
             ErrorMessage="RegularExpressionValidator" 
             ValidationExpression="(?i)^[\w\s0-9.-]+\.(txt|pdf|doc|docx|xls|xlsx)$" 
             ValidationGroup="FileUpload">
             * Please upload file in format .pdf / .docx / .xlsx.
        </asp:RegularExpressionValidator>
     </td>
   </tr>
  </table>   
        <asp:Label ID="lblfileuploaded" runat="server" Text=""></asp:Label>

到目前为止,我的代码是VB页面:

Protected Function GetUploadList() As String()
            Dim folder As String = Server.MapPath("~/Uploads")
    Dim files() As String = Directory.GetFiles(folder)
    Dim fileNames(files.Length - 1) As String
    Array.Sort(files)

    For i As Integer = 0 To files.Length - 1
        fileNames(i) = "<a href=""Uploads/" & Path.GetFileName(files(i).ToString()) & """ target=""_blank"">" & Path.GetFileName(files(i)) & "</a>"
    Next

    Return fileNames
End Function

   Protected Sub UploadThisFile(ByVal upload As FileUpload)
    If upload.HasFile Then
        Dim theFileName As String = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName)

        If File.Exists(theFileName) Then
            File.Delete(theFileName)
        End If

        upload.SaveAs(theFileName)
    End If
End Sub

Protected Sub buttonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonUpload.Click
    UploadThisFile(FileUpload1)
    UploadedFiles.DataBind()
End Sub

非常感谢您提前获得的任何帮助。

1 个答案:

答案 0 :(得分:1)

正如Tim Schmelter所说in the comments,您应该在成功调用SaveAs后设置标签文字。

您可以使用Try - &gt; Catch以确保没有例外(根据上面链接的MSDN文章,SaveAs方法可能会抛出HttpException)。像这样:

Try
    upload.SaveAs(theFileName)
    fileuploaded.Text="File uploaded successfully"
Catch ex As Exception
    fileuploaded.Text="Upload failed.  Reason: " + ex.Message