Solved

fileUpload in ASP.NET

Posted on 2006-07-23
26
1,879 Views
Last Modified: 2013-11-25
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
Comment
Question by:absalax
  • 15
  • 10
26 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 250 total points
ID: 17163655
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
 

Author Comment

by:absalax
ID: 17163883

Hi,

I will try putting this in my sub UploadBtn_Click,

I'll give you a feedback after testing it.

thanks

0
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17163892
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
 

Author Comment

by:absalax
ID: 17164172

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
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17164186
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
 

Author Comment

by:absalax
ID: 17164216


Thanks TheMeg...


I'll do that right now
0
 

Author Comment

by:absalax
ID: 17164262

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
 

Author Comment

by:absalax
ID: 17164310


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
 
LVL 12

Assisted Solution

by:TheMegaLoser
TheMegaLoser earned 250 total points
ID: 17164466
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
 

Author Comment

by:absalax
ID: 17165811


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
 

Author Comment

by:absalax
ID: 17165887
Could anyone please help
0
 
LVL 12

Assisted Solution

by:TheMegaLoser
TheMegaLoser earned 250 total points
ID: 17165917
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
 

Author Comment

by:absalax
ID: 17165957
<asp:FileUpload ID="FileUpload1" Runat="server" />

thats my fileupload, is there something wrong with it
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:absalax
ID: 17165983
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
 

Author Comment

by:absalax
ID: 17166050
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
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17166087
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
 

Author Comment

by:absalax
ID: 17166204

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
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17166264
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
 

Author Comment

by:absalax
ID: 17166340
<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
 
LVL 12

Assisted Solution

by:TheMegaLoser
TheMegaLoser earned 250 total points
ID: 17166400
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
 

Author Comment

by:absalax
ID: 17166404

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
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17166425
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
 

Author Comment

by:absalax
ID: 17166475

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
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17166518
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
 

Author Comment

by:absalax
ID: 17166538


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

Now all solved.

Many Thanks
0
 
LVL 12

Expert Comment

by:TheMegaLoser
ID: 17166553
Great :)
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
After several hours of googling I could not gather any information on this topic. There are several ways of controlling the USB port connected to any storage device. The best example of that is by changing the registry value of "HKEY_LOCAL_MACHINE\S…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now