Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1897
  • Last Modified:

fileUpload in ASP.NET

Hi,

I have the following sub for uploading files for my application

Protected Sub UploadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ' Specify the path on the server to
        ' save the uploaded file to.
        Dim savePath As String = "C:\notes\Reports\"
           
        ' verify that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then
           
            ' Get the name of the file to upload.
            Dim fileName As String = Server.HtmlEncode(FileUpload1.FileName)
           
            ' Get the extension of the uploaded file.
            Dim extension As String = System.IO.Path.GetExtension(fileName)
           
            ' Allow only files with .pdf to be uploaded.
            If (extension = ".pdf") Then
                       
                ' Append the name of the file to upload to the path.
                savePath += fileName
           
                ' Call the SaveAs method to save the
                ' uploaded file to the specified path.
                ' If a file with the same name
                ' already exists in the specified path,  
                ' the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath)
               
                ' Notify the user that their file was successfully uploaded.
                UploadStatusLabel.Text = "Your file was uploaded successfully."
           
            Else
                ' Notify the user why their file was not uploaded.
                UploadStatusLabel.Text = "Your file was not uploaded because " + _
                                         "it is not an 'Adobe PDF' file"
            End If
               
        Else
            ' Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload."
        End If
    End Sub

There is one new condition I want to add besides allowing only pdf files:
 I would like the file to be uploaded to have a format like xx_yy_zz, if the condition is not met, the file should not be uploaded. How do I do this.


Secondly, in a situation where a user is trying to upload a file and a similar file already exists,  I would like the application to ask/confirm, before over writing the existing file. How do I do this.

Please help this is urgent.

Thanks
0
absalax
Asked:
absalax
  • 15
  • 10
4 Solutions
 
Bob LearnedCommented:
You could use a regular expression:

Imports System.Text.RegularExpressions

Public Class Validation

  Public Shared Function IsValidFileName(ByVal input As String) As Boolean

    Dim pattern As String = "[A-Z\d]{2}_[A-Z\d]{2}_[A-Z\d]{2}"

    Return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase)

  End Function

End Class

Bob
0
 
absalaxAuthor Commented:

Hi,

I will try putting this in my sub UploadBtn_Click,

I'll give you a feedback after testing it.

thanks

0
 
TheMegaLoserCommented:
Before saving a file, check if the file exists (System.IO.File.Exists(savePath)). If it does, save it to a temporary file, show the user a page where he/she can select what to do. Pass the temporary filename along with the answer back to the server. If the user answered no, delete the file, if yes, move it over the old file.

Alternatively, make sure each file get a new filename by adding a GUID for example.

savePath += System.Guid.NewGuid.ToString + fileName
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
absalaxAuthor Commented:

Hi TheLearnedOne,

I'm very new to asp.net and need you to please clarify this just to save me time.
How do I integrate this class with my sub UploadBtn_Click.
Right now  sub UploadBtn_Click is fired from 'onclick' of fileupload server control

Thanks
0
 
TheMegaLoserCommented:
absalax, paste TheLearnedOne's code above your sub Uploadbtn, then create a new if cluase that calls the function.

If Validation.IsValidFileName(fileName) Then
  ' all ok
Else
 ' Invalid Filename
End If
0
 
absalaxAuthor Commented:


Thanks TheMeg...


I'll do that right now
0
 
absalaxAuthor Commented:

Thanks TheMega... and TheLearnedOne,

I used the class and added the new condition.  Here is the exact code below just for other users

Imports System.Text.RegularExpressions

Partial Class _Default
    Inherits System.Web.UI.Page

    Public Class Validation

        Public Shared Function IsValidFileName(ByVal input As String) As Boolean

            Dim pattern As String = "[A-Z\d]{2}_[A-Z\d]{2}_[A-Z\d]{2}"

            Return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase)

        End Function

    End Class


    Protected Sub UploadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ' Specify the path on the server to
        ' save the uploaded file to.
        Dim savePath As String = "C:\Upload\"

        ' verify that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then

            ' Get the name of the file to upload.
            Dim fileName As String = Server.HtmlEncode(FileUpload1.FileName)

            ' Get the extension of the uploaded file.
            Dim extension As String = System.IO.Path.GetExtension(fileName)

            ' Allow only files with .pdf to be uploaded.
            If (extension = ".pdf") And (Validation.IsValidFileName(fileName)) Then

                ' Append the name of the file to upload to the path.
                savePath += fileName

                ' Call the SaveAs method to save the
                ' uploaded file to the specified path.
                ' If a file with the same name
                ' already exists in the specified path,  
                ' the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath)

                ' Notify the user that their file was successfully uploaded.
                Label1.Text = "Your file was uploaded successfully."

            Else
                ' Notify the user why their file was not uploaded.
                Label1.Text = "Your file was not uploaded because " + _
                                         "it is not an 'Adobe PDF' file" + _
                                         "or the file name is not like xx_yy_zz"
            End If

        Else
            ' Notify the user that a file was not uploaded.
            Label1.Text = "You did not specify a file to upload."
        End If
    End Sub

End Class
0
 
absalaxAuthor Commented:


Hi TheMegaL...

For reusability,
I want to save the class in a separate file called Validation.

How do I call it up in my sub UploadBtn_Click?

thanks



0
 
TheMegaLoserCommented:
Short answer: The same way.

Long answer: TheLearnedOne already thought of this and put the Validation code in a separate class. Create the new file and call it Validation. Then add the shared Function to the class and it should work.

The Validation in Validation.IsValidFileName(fileName) tells .NET to look for the function in a class (or namespace) called Validation. It will then resolve the class in either your main code or another assembly thats part of your project.
0
 
absalaxAuthor Commented:


Hi Mega...,
I wanted to know if I needed to create a new instance of the validation class whenever I want to use it. Do I need to create a new instance of validation class  before using it?

Here is something slightly different,
I am getting an error with this statements (FileUpload1.HasFile) and (FileUpload1.FileName)

It says HasFile and FileNames are not members of System.Web.UI.Control
==========================================================

Secondly, I am trying to do a FindControl  for my label control because it is in my edit template of a formview

Label1() = FormView1.Controls.Item(0).Controls(0).FindControl("Label1")

I get error - Class System.Web.UI.Control can not be indexed because it has no default property

Please help, thanks
0
 
absalaxAuthor Commented:
Could anyone please help
0
 
TheMegaLoserCommented:
Since the function is "Shared" you do not have to create an instance of the class.

To asnwer your first new question I need to know what type of control FileUpload1 is. It should be of System.Web.UI.WebControls.FileUpload. Either you have created it incorrectly or you have to cast it to a FileUpload control

Casting:
FileUploadCtrl = DirectCast(FileUpload1, FileUpload1)

Second question, you have missed the to include the Items collection on the Control collection, ie:
Label1() = FormView1.Controls.Item(0).Controls.Item(0).FindControl("Label1")
0
 
absalaxAuthor Commented:
<asp:FileUpload ID="FileUpload1" Runat="server" />

thats my fileupload, is there something wrong with it
0
 
absalaxAuthor Commented:
your suggestion for the label1 problem is not solved

I used the syntax for fileupload1, and it works,
FileUpload1 = FormView1.Controls.Item(0).Controls(0).FindControl("FileUpload1")

0
 
absalaxAuthor Commented:
Here is my entire code

Protected Sub UploadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim FileUpload1 As New System.Web.UI.Control
        Dim Label1 As New System.Web.UI.Control
        Dim savePath As String = "C:\Upload\"
       
        ' Specify the path on the server to
        ' save the uploaded file to.
        If FormView1.CurrentMode = FormViewMode.Edit Then
            FileUpload1 = FormView1.Controls.Item(0).Controls(0).FindControl("FileUpload1")
            Label1() = FormView1.Controls.Item(0).Controls.Item(0).FindControl("Label1")
        End If

        ' verify that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then

            ' Get the name of the file to upload.
            Dim fileName As String = Server.HtmlEncode(FileUpload1.FileName)

            ' Get the extension of the uploaded file.
            Dim extension As String = System.IO.Path.GetExtension(fileName)

            ' Allow only files with .pdf to be uploaded.
            If (extension = ".pdf") And (Validation.IsValidFileName(fileName)) Then

                ' Append the name of the file to upload to the path.
                savePath += fileName

                ' Call the SaveAs method to save the
                ' uploaded file to the specified path.
                ' If a file with the same name
                ' already exists in the specified path,  
                ' the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath)

                ' Notify the user that their file was successfully uploaded.
                Label1.Text = "Your file was uploaded successfully."

            Else
                ' Notify the user why their file was not uploaded.
                Label1.Text = "Your file was not uploaded because " + _
                                         "it is not an 'Adobe PDF' file" + _
                                         "or the file name is not like xx_yy_zz"
            End If

        Else
            ' Notify the user that a file was not uploaded.
            Label1.Text = "You did not specify a file to upload."
        End If
    End Sub


0
 
TheMegaLoserCommented:
You have only modified the label row, not the file upload row

Code should read (cant be certain without the aspx though)

       ' Specify the path on the server to
        ' save the uploaded file to.
        If FormView1.CurrentMode = FormViewMode.Edit Then
            FileUpload1 = FormView1.Controls.Item(0).Controls.Item(0).FindControl("FileUpload1")
            Label1 = FormView1.Controls.Item(0).Controls.Item(0).FindControl("Label1")
        End If
0
 
absalaxAuthor Commented:

The find control error is gone now.

Its the properties below that still have the errors

FileUpload1.HasFile ..............not a member of  not members of System.Web.UI.Control
FileUpload1.FileName............not a member of  not members of System.Web.UI.Control
FileUpload1.SaveAs...............not a member of  not members of System.Web.UI.Control
Label1.text............................not a member of  not members of System.Web.UI.Control

thank you
0
 
TheMegaLoserCommented:
How does your tag look in the aspx page? Does it look like

<asp:fileupload ...

or

<input type=file ...

Which version of .NET are you using?
0
 
absalaxAuthor Commented:
<asp:FileUpload ID="FileUpload1" Runat="server" />
                <p>
 <asp:Button ID="Button1" Runat="server" Text="Upload" OnClick="UploadBtn_Click" />
                <br />
<asp:Label ID="Label1" Runat="server"></asp:Label></p>


ASP.NET 2.0
0
 
TheMegaLoserCommented:
Change these lines:

Dim FileUpload1 As New System.Web.UI.Control
Dim Label1 As New System.Web.UI.Control

To

Dim FileUpload1 As New System.Web.UI.WebControls.FileUpload
Dim Label1 As New System.Web.UI.WebControls.Label
0
 
absalaxAuthor Commented:

I haven't tried casting, can you please insert it in the palce where it should be in my code (its new to me)
0
 
TheMegaLoserCommented:
You dont have to do casting to access the properties you want if you make the change suggested two comments up.

You might have to do casting at the following lines though:

FileUpload1 = FormView1.Controls.Item(0).Controls.Item(0).FindControl("FileUpload1")
Label1 = FormView1.Controls.Item(0).Controls.Item(0).FindControl("Label1")

Change to the following then:

FileUpload1 = DirectCast(FormView1.Controls.Item(0).Controls.Item(0).FindControl("FileUpload1"), FileUpload)
Label1 = DirectCast(FormView1.Controls.Item(0).Controls.Item(0).FindControl("Label1"), Label)

THere are two different cast functions (actually there are more ways but I'll describe two here)

DirectCast - Tries to make the cast and throws an exception if it doesn't succeed
TryCast - Tries to make the cast and returns null/nothing if it doesn't succeed

If you want to use TryCast instead, just replace DirectCast in the example above
0
 
absalaxAuthor Commented:

I tried casting, it still didn't work. Still same error

FileUpload1.HasFile .............. not members of System.Web.UI.Control
FileUpload1.FileName............not a member of System.Web.UI.Control
FileUpload1.SaveAs...............not a member of System.Web.UI.Control
Label1.text............................not a member of System.Web.UI.Control
0
 
TheMegaLoserCommented:
Looks like you still havent done these changes mentioned above:

Change these lines:

Dim FileUpload1 As New System.Web.UI.Control
Dim Label1 As New System.Web.UI.Control

To

Dim FileUpload1 As New System.Web.UI.WebControls.FileUpload
Dim Label1 As New System.Web.UI.WebControls.Label
0
 
absalaxAuthor Commented:


Yes you're right, I skipped that step...an oversight.

Now all solved.

Many Thanks
0
 
TheMegaLoserCommented:
Great :)
0

Featured Post

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

  • 15
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now