This article shows that how can you upload the images and show them on page in a DataList. The uploaded images will save in a folder in your system.
The MyAlbum.aspx code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>My Album</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" width="90%" border="4" align="center">
<tr><td align="center">
<br />
<asp:Label ID="lblMyAlbum" Text="My Album" ForeColor="Blue"
Font-Bold="true" Font-Size="14pt" runat="server">
</asp:Label>
<br /><br />
<asp:Label ID="lblImageFile" runat="server" AssociatedControlID="UpImage"
Text="Image File"> </asp:Label>
<asp:FileUpload ID="UpImage" runat="server" />
<asp:Button ID="btnAdd" Text="Add An Image" runat="server" OnClick="btnAdd_Click" />
<br /><br />
<asp:DataList ID="dlstImage" RepeatColumns="4" runat="server">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%#Eval("Name","~/UploadImages/{0}") %>' Width="200px"
runat="server" BorderColor="#006600" />
<br />
</ItemTemplate>
</asp:DataList>
</td></tr>
</table>
</div>
</form>
</body>
</html>
The Album.aspx.cs code is:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Prerender(object sender, EventArgs e)
{
string UpFolder = Server.MapPath("~/UploadImages/");
DirectoryInfo dir = new DirectoryInfo(UpFolder);
dlstImage.DataSource = dir.GetFiles();
dlstImage.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (UpImage.HasFile)
{
if (CheckFileType(UpImage.FileName))
{
string FilePath = "~/UploadImages/" + UpImage.FileName;
UpImage.SaveAs(Server.MapPath(FilePath));
}
}
}
public bool CheckFileType(string FileName)
{
string Ext = Path.GetExtension(FileName);
switch(Ext.ToLower())
{
case ".gif" :
return true ;
break;
case ".JPEG":
return true;
break;
case ".JPG":
return true;
break;
case ".png":
return true;
break;
default:
return false;
break;
}
}
}