?
Solved

Changing Filename via code using FileUploader Control

Posted on 2006-04-26
6
Medium Priority
?
252 Views
Last Modified: 2011-10-03
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.
0
Comment
Question by:baasassasin
  • 3
  • 3
6 Comments
 
LVL 8

Accepted Solution

by:
rodmjay earned 2000 total points
ID: 16550681

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
0
 

Author Comment

by:baasassasin
ID: 16554657
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.
0
 

Author Comment

by:baasassasin
ID: 16554929
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
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 8

Expert Comment

by:rodmjay
ID: 16555328
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.
0
 

Author Comment

by:baasassasin
ID: 16556282
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 ;)
0
 
LVL 8

Expert Comment

by:rodmjay
ID: 16556620
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
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses
Course of the Month13 days, 9 hours left to enroll

750 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