Upload an IMAGE in ASP.Net

 

ASP.Net Code

Private Sub Upload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim savePath As String
Dim thumbExtension As String
Dim tHeight As Int32
Dim tWidth As Int32

savePath = "images/"
thumbExtension = "_thumb"
tHeight = 160
tWidth = 120
Dim chk As Boolean
Dim fileString() As String
Dim a As String
chk = checkfile()
Dim filename As String = fileUpload.PostedFile.FileName
fileString = filename.Split("\")
a = fileString(UBound(fileString))

If chk Then

Dim myFile As HttpPostedFile = fileUpload.PostedFile

If fileUpload.PostedFile.ContentLength = 0 Then
Label1.Text = "No Files Selected"
Return
End If

If System.IO.Path.GetExtension(a).ToLower <> ".jpg" Then
Label1.Text = "The uploaded file has an extension" & System.IO.Path.GetExtension(a) & ". File must have extension .jpg"
Return
End If

Dim myData(fileUpload.PostedFile.ContentLength) As Byte
myFile.InputStream.Read(myData, 0, fileUpload.PostedFile.ContentLength)

Dim file_append As Int32 = 0

While (System.IO.File.Exists(Server.MapPath(savePath + a)))
file_append = file_append + 1
a = System.IO.Path.GetFileNameWithoutExtension(a) & file_append & ".jpg"
End While

Dim newfile As New System.IO.FileStream(Server.MapPath(savePath & a), IO.FileMode.Create)
newfile.Write(myData, 0, myData.Length)
newfile.Close()

Image1.ImageUrl = savePath & a

End If

End Sub

Public Function checkfile() As Boolean
If fileUpload.PostedFile.FileName = "" Then Return False
If fileUpload.PostedFile.ContentLength = 0 Then Return False
Return True
End Function

HTML Code To be Noted

<form id="Form1" method="post" encType="multipart/form-data" runat="server">
<INPUT id="fileUpload" style="Z-INDEX: 101; LEFT: 416px; POSITION: absolute; TOP: 160px"
type="file" name="fileUpload" runat="server" onpropertychange="show()">
</form>

JavaScript Code

<script language="javascript">
function show()
{
document.getElementById("Image1").src=document.getElementById("fileUpload").value;
}
</script>