Dim sSavePath As String
Dim sThumbExtension As String
Dim intThumbWidth As Integer
Dim intThumbHeight As Integer
Dim sFilename As String
sSavePath = "C:\Suretxtlog\Pictures\" '"~/images/"
sThumbExtension = "_thumb"
intThumbWidth = 160
intThumbHeight = 120
'If file field isnt empty
If IsNothing(filUpload.PostedFile) = False Then
Dim myFile As HttpPostedFile = filUpload.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
'Check file size (mustnt be 0)
If nFileLen = 0 Then
lblOutput.Text = "No file was uploaded."
Return
End If
'Check file extension (must be JPG)
If 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 a data stream
Dim myData() As Byte = New Byte(nFileLen) {}
myFile.InputStream.Read(myData, 0, nFileLen)
'Make sure a duplicate file doesnt exist. If it does, keep on appending an incremental numeric until it is unique
sFileName = System.IO.Path.GetFileName(myFile.FileName)
Dim file_append As Integer = 0
While System.IO.File.Exists(sSavePath & sFilename)
file_append = file_append & 1
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) & file_append.ToString() & ".jpg"
End While
'Save the stream to disk
Dim newFile As System.IO.FileStream = New System.IO.FileStream(sSavePath & sFilename, System.IO.FileMode.Create)
newFile.Write(myData, 0, myData.Length)
newFile.Close()
' Check whether the file is really a JPEG by opening it
Try
' If jpg file is a jpeg, create a thumbnail filename that is unique.
file_append = 0
Dim sThumbFile As String = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) & sThumbExtension & ".jpg"
While System.IO.File.Exists(sSavePath & sThumbFile)
file_append = file_append & 1
sThumbFile = sThumbFile & file_append
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) & file_append.ToString(sThumbExtension & ".jpg")
End While
Dim ThumbnailCallback As System.Drawing.Image.GetThumbnailImageAbort
Dim myCallBack As System.Drawing.Image.GetThumbnailImageAbort
' Save thumbnail and output it onto the webpage
Dim mybitmap As Bitmap
mybitmap = New Bitmap(sSavePath & sFilename)
Dim mythumbnail As System.Drawing.Image
mythumbnail = mybitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero)
mythumbnail.Save(sSavePath & sThumbFile)
imgPicture.ImageUrl = sSavePath & sThumbFile
' Displaying success information
lblOutput.Text = "File uploaded successfully!"
' Destroy objects
mythumbnail.Dispose()
mybitmap.Dispose()
Catch errArgument As ArgumentException
' The file wasn't a valid jpg file
lblOutput.Text = "The file wasn't a valid jpg file."
System.IO.File.Delete(sSavePath & sFilename)
End Try
End If