2

我一直在我的 ASP.NET 站点中处理文件上传部分。

使用下面的代码,我可以让用户根据RegularExpressionValidator. 我很高兴这能相应地工作。

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

这是我的 .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

非常感谢您提前提供任何帮助。

4

1 回答 1

1

正如Tim Schmelter在评论中所说,您应该在SaveAs成功调用后设置标签的文本。

您可以使用Try->Catch来确保没有异常(根据上面链接的 MSDN 文章,该SaveAs方法可能会抛出HttpException)。像这样的东西:

Try
    upload.SaveAs(theFileName)
    fileuploaded.Text="File uploaded successfully"
Catch ex As Exception
    fileuploaded.Text="Upload failed.  Reason: " + ex.Message
于 2012-05-16T13:49:36.610 回答