Uploading image using InputFile control in ASP.NET

By bryan tugade

We can upload image in our web application using input file html control in VB.NET. By assigning this control to runat=”server”, we can access its attribute in code behind.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="upload_Photo_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="File1" type="file" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" />
</div>
</form>
</body>
</html>


And in our code behind

Imports System.IO

Partial Class upload_Photo_Default
Inherits System.Web.UI.Page

Private Function uploadphoto() As String
Dim fullurlofImage As String
'change this url into your url apps
Dim imgFolder As String = "http://localhost:49157/EggHeadCafe_snippets/"

If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
Dim extension As String = Path.GetExtension(File1.PostedFile.FileName).ToLower()
Dim MIMEType As String = Nothing
Select Case extension
Case ".jpg", ".jpeg", ".jpe"
MIMEType = "image/jpeg"

Case Else

Response.Write("Please input correct valid photo, please try again.")
Return Nothing
Exit Function

End Select
Dim dir As String = Context.Request.PhysicalApplicationPath
Dim imgName As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
File1.PostedFile.SaveAs(dir & "images\" & imgName)
fullurlofImage = imgFolder & imgName
Return fullurlofImage
Catch ex As Exception
'create error handler here...
End Try

End If

End Function

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
uploadphoto()
Else
Response.Write("There no selected image.")


End If
Catch ex As Exception

End Try


End Sub
End Class

Related FAQs

How to use AJAX AsyncFileUpload Control for uploading image and validate if the file is jpeg extension.
We can upload image in our web application using input file html control. By assigning this control to runat=”server”, we can access its attribute in code behind.
How to use AJAX AsyncFileUpload Control for uploading image and validate if the file is jpeg extension.
Uploading image using InputFile control in ASP.NET  (2608 Views)