Changing Filename via code using FileUploader Control

This is a two fold question:
  1) Could someone show me in code how to make a fileuploader control that is like the current one on the visual toolbar?  The one there is fine but lets say I want to change the name of the browse button or I want to change the location of the textbox for the path. I don't see a way of doing that in the properties so making it myself would be a better sollution I would think. I understand how to make the textbox and the onclick event but the reason I picked this control was for the fact it allowed for browsing.

2) How do you change the name of a file that has been uploaded. Lets say for instance you have  dsc1001.jpg but you want the picture be matched to that of an employeeID say 7  how would you change it to 7.jpg?   I know you could make filename.text or whatever = to 7.jpg but that would mess up the actual source path before upload would it not?  What I'm shooting for is the ability to upload an image and then when it post to the server have the server instantly change its name to <EmployeeID>.jpg

I know how to to use the UI control but I want to see this done manual in code so it can be modified. Thanks in advance for your help.
baasassasinAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rodmjayCommented:

here is the code that i user for one of my projects, you should be able to recognize what the code is doing it does what you are trying to do

            Dim sSavePath As String

            sSavePath = ResolveUrl("~/Images/Products/")

            'If file field isn't empty
            If Not filUpload.PostedFile Is Nothing Then

                'Check file size
                Dim myFile As HttpPostedFile = filUpload.PostedFile
                Dim nFileLen As Integer = myFile.ContentLength
                If nFileLen = 0 Then
                    lblOutput.Text = "No file was uploaded."
                    Return
                End If

                'Check file extension
                If Not System.IO.Path.GetExtension(myFile.FileName).ToLower = ".jpg" Then
                    lblOutput.Text = "The file must have an extension of JPG"
                    Return
                End If

                'Read file into data stream
                Dim myData(nFileLen) As Byte
                myFile.InputStream.Read(myData, 0, nFileLen)

                'Make sure a duplicate file doesn't exist. If it does, keep on appending an
                'incremental numeric unit until its unique
                Dim sFilename As String = myPartNumber + "{0}" + ".jpg"
                Dim file_append As Integer = 0
                While System.IO.File.Exists(Server.MapPath(sSavePath + sFilename))
                    file_append += 1
                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + _
                        file_append.ToString + ".jpg"
                End While

                'Save the steam to disk
                Dim newFile As System.IO.FileStream = _
                    New System.IO.FileStream(Server.MapPath(sSavePath + String.Format(sFilename, sHiExtension)), IO.FileMode.Create)
                newFile.Write(myData, 0, myData.Length)
                newFile.Close()

                'Check whether the file is really a jpeg by opening it
                Dim myCallBack As System.Drawing.Image.GetThumbnailImageAbort = _
                    New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)
                Dim myBitmap As Bitmap
                Try
                    myBitmap = New Bitmap(Server.MapPath(sSavePath + String.Format(sFilename, sHiExtension)))

                    'If jpg file is a jpeg, create a thumbnail filename that is unique
                    file_append = 0
                    Dim sThumbFile As String = System.IO.Path.GetFileNameWithoutExtension(String.Format(sFilename, sThumbExtension)) + ".jpg"
                    While System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile))
                        file_append += 1
                        sThumbFile = System.IO.Path.GetFileNameWithoutExtension(String.Format(sFilename, sThumbExtension) + _
                            file_append.ToString + ".jpg")
                    End While

                    'Maintain ratio of the image
                    Dim intImgWidth As Integer = myBitmap.Width
                    Dim intImgHeight As Integer = myBitmap.Height

                    Dim sngRatio As Single = intImgWidth / intImgHeight

                    'If the width is greater than the height
                    If intImgWidth > intImgHeight Then
                        'Use the width as the aspect rule
                        intImgWidth = intThumbWidth
                        intImgHeight = intImgWidth / sngRatio

                    ElseIf intImgWidth <= intImgHeight Then
                        'Use the height as the aspect rule
                        intImgHeight = intThumbHeight
                        intImgWidth = intImgHeight * sngRatio
                    End If


                    'Save thumbnail and output it onto the webpage
                    Dim myThumbnail As System.Drawing.Image = _
                        myBitmap.GetThumbnailImage(intImgWidth, intImgHeight, myCallBack, IntPtr.Zero)
                    myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile))
                    imgPicture.ImageUrl = sSavePath + sThumbFile

                    'Displaying success information
                    lblOutput.Text = "File uploaded successfully!"

                    'Destroy objects
                    myThumbnail.Dispose()

                    'Generate web image as well
                    myBitmap = New Bitmap(Server.MapPath(sSavePath + String.Format(sFilename, sHiExtension)))

                    'If jpg file is a jpeg, create a thumbnail filename that is unique
                    file_append = 0
                    Dim sWebFile As String = System.IO.Path.GetFileNameWithoutExtension(String.Format(sFilename, sWebExtension)) + ".jpg"
                    While System.IO.File.Exists(Server.MapPath(sSavePath + sWebFile))
                        file_append += 1
                        sWebFile = System.IO.Path.GetFileNameWithoutExtension(String.Format(sFilename, sWebExtension) + _
                            file_append.ToString + ".jpg")
                    End While

                    'Maintain ratio of the image
                    intImgWidth = myBitmap.Width
                    intImgHeight = myBitmap.Height

                    sngRatio = intImgWidth / intImgHeight

                    'If the width is greater than the height
                    If intImgWidth > intImgHeight Then
                        'Use the width as the aspect rule
                        intImgWidth = intWebWidth
                        intImgHeight = intImgWidth / sngRatio

                    ElseIf intImgWidth <= intImgHeight Then
                        'Use the height as the aspect rule
                        intImgHeight = intWebHeight
                        intImgWidth = intImgHeight * sngRatio
                    End If


                    'Save thumbnail and output it onto the webpage
                    Dim myWebImage As System.Drawing.Image = _
                        myBitmap.GetThumbnailImage(intImgWidth, intImgHeight, myCallBack, IntPtr.Zero)
                    myWebImage.Save(Server.MapPath(sSavePath + sWebFile))
                    imgWebPicture.ImageUrl = sSavePath + sWebFile
                    imgHiPicture.ImageUrl = sSavePath + String.Format(sFilename, sHiExtension)

                    'Displaying success information
                    lblOutput.Text = "File uploaded successfully!"

                    'Destroy objects
                    myWebImage.Dispose()
                    myBitmap.Dispose()

                Catch ex As Exception

                    'The file wasn't a valid jpg file
                    lblOutput.Text = "The file wasn't a valid jpg file."
                    'System.IO.File.Delete(Server.MapPath(sSavePath + sFilename))
                    Throw ex
                End Try

            End If

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
baasassasinAuthor Commented:
Thanks that is the answer I was looking for. I will try to implement this into my code and will ask additional question if any arrise. Thanks again.
baasassasinAuthor Commented:
One more question for you. First off I modified your code to meet my needs and converted it into a modular subroutine. In any event, I can't seem to understand what siHiExtention needs to be declared at and the compiler is shakin its finger at me saying sHiExtention is not declared. Could you please help thanks.
Here is my code:

#Region "UPload a Jpeg Function"
    Public Sub UploadAnImage(ByVal FilUpload As System.Web.UI.WebControls.FileUpload, ByVal FileUploadReport As Label, ByVal ImgPrevew As Image, ByVal EmployeeID As Integer)

        Dim sSavePath As String
        sSavePath = ResolveUrl("C:\Inetpub\pedalvalve\Mugshots\")
        Try
            'If file field isn't empty
            If Not FilUpload.PostedFile Is Nothing Then

                'Check file size
                Dim myFile As HttpPostedFile = FilUpload.PostedFile
                Dim nFileLen As Integer = myFile.ContentLength
                If nFileLen = 0 Then
                    FileUploadReport.Text = "No file was uploaded."
                    Return
                End If

                'Check file extension
                If Not System.IO.Path.GetExtension(myFile.FileName).ToLower = ".jpg" Then
                    FileUploadReport.Text = "The file must have an extension of JPG"
                    Return
                End If

                'Read file into data stream
                Dim myData(nFileLen) As Byte
                myFile.InputStream.Read(myData, 0, nFileLen)

                'Make sure a duplicate file doesn't exist. If it does, keep on appending an
                'incremental numeric unit until its unique
                Dim sFilename As String = EmployeeID + ".jpg"

                While System.IO.File.Exists(Server.MapPath(sSavePath + sFilename))
                    System.IO.File.Delete(Server.MapPath(sSavePath + sFilename)) '' delete the old image and store the new one!
                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + ".jpg"
                End While

                'Save the steam to disk
                Dim newFile As System.IO.FileStream = _
                    New System.IO.FileStream(Server.MapPath(sSavePath + String.Format(sFilename, sHiExtension)), IO.FileMode.Create)
                newFile.Write(myData, 0, myData.Length)
                newFile.Close()



                'Displaying success information
                FileUploadReport.Text = "File uploaded successfully!"





            End If
        Catch ex As Exception

            'The file wasn't a valid jpg file
            FileUploadReport.Text = "The file wasn't a valid jpg file."

            Throw ex
        End Try


    End Sub
#End Region
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

rodmjayCommented:
oh, sorry, what i was doing in this case was saving three versions of the same file, for example the hi resolution file, the lo resolution file, etc.

You can simple ignore these types of things, delete the entire string.format clause and replace with any string you want your files to be named.
baasassasinAuthor Commented:
Still a bit confused rodmjay
I'm not getting any errors nor Is the file being placed on the server. I set a breakpoint in the debugger but for some reason  beyond me its not breaknig so I can see what the path path variable is.
have a look at http://pastebin.com/685519 thats the codebehind for my addemployee noticed the highlight on line 310

here is my class.....
please take note of the highlighted section which is the subroutine for the update method http://pastebin.com/685529

Thanks in advance. Almost got it but still playing battleship and missing the boat ;)
rodmjayCommented:
Here is the link from which i got the code, i modified it, but here is the real thing

http://www.codeproject.com/aspnet/netimageupload.asp
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.