Uploading image using InputFile control in C#
By bryan tugade
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.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
public partial class uploadimageinc_Default : System.Web.UI.Page
{
private string uploadphoto()
{
string functionReturnValue = null;
string fullurlofImage = null;
//change this url into your url apps
string imgFolder = "http://localhost:49223/eggheadcafe/images";
string MIMEType = null;
if ((File1.PostedFile != null) & File1.PostedFile.ContentLength > 0)
{
try
{
string extension = Path.GetExtension(File1.PostedFile.FileName).ToLower();
switch (extension)
{
case ".jpg":
MIMEType = "image/jpeg";
break;
case ".jpe":
MIMEType = "image/jpeg";
break;
default:
Response.Write("Please input correct valid photo, please try again.");
return null;
}
string dir = Context.Request.PhysicalApplicationPath;
string imgName = System.IO.Path.GetFileName(File1.PostedFile.FileName);
File1.PostedFile.SaveAs(dir + "images\\" + imgName);
fullurlofImage = imgFolder + imgName;
return fullurlofImage;
}
catch (Exception ex)
{
//create error handler here...
}
}
return functionReturnValue;
}
protected void Button1_Click1(object sender, EventArgs e)
{
try
{
if ((File1.PostedFile != null) & File1.PostedFile.ContentLength > 0)
{
uploadphoto();
}
else
{
Response.Write("There no selected image.");
}
}
catch (Exception ex)
{
//create handler here....
}
}
}
Uploading image using InputFile control in C# (1281 Views)