Sunday, 24 July 2011

Upload with Thumbnail Generator in ASP.NET and C#


This tutorial will show how we use the FileUpload Control to upload a file to the website, whilst simultaneously creating a thumbnail of the image, and saving that too. C# version.

In this tutorial, we will create a single file upload form and a GridView to display the list of uploaded files.
The upload form will upload a single file at a time, when the user click the button, and it will also create a thumbnail of the image, saving both images to the uploads folder.

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

First, we add the controls to the ASPX page (FileUpload, Button, and GridView):
<form id="form1" runat="server">
<div>
<table style="width: 90%">
<tr>
<td style="width: 50%">
File Upload with Thumbnail Generator:<br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="buttonUpload" runat="server" Text="Upload" OnClick="buttonUpload_Click" /><br />
</td>
<td style="width: 50%">
<asp:GridView ID="UploadedFiles" DataSource="<%# GetUploadList() %>" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="UploadedFiles_RowDeleting" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="File">
<ItemStyle Width="100%" />
<ItemTemplate>
<asp:HyperLink
ID="FileLink"
NavigateUrl='<%# "~/Uploads/" + Container.DataItem.ToString() %>'
Text='<%# Container.DataItem.ToString() %>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" DeleteImageUrl="~/media/delete.gif" ShowDeleteButton="True">
<ItemStyle Width="1px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

The GetUploadList() function will retrieve a list of filenames in the uploads directory, and then insert them into an array. The function returns an array of all the filenames in the upload folder.
The buttonUpload_click event first checks to see if the file exists; if it does not, then it saves it to the uploads directory. Then the image is analyzed (height & width), and then resized to 128px. Finally, the thumbnail is created and saved to the uploads directory with "_th" added to the end of the filename, and the GridView is updated.
The UploadedFiles_RowDeleting function allows the user to delete any file in the GridView by simply clicking the icon.
The code-behind will look something like this:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.Security;
using System.Web.Profile;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.IO;

partial class _Default : System.Web.UI.Page
{
override protected void OnInit(EventArgs e)
{

}

override protected void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (! IsPostBack)
{
UploadedFiles.DataBind();
}
}

protected string[] GetUploadList()
{
string folder = Server.MapPath("~/Uploads");
string[] files = Directory.GetFiles(folder);
string[] fileNames = new string[files.Length];
Array.Sort(files);

for (int i = 0; i < files.Length; i++)
{
fileNames[i] = Path.GetFileName(files[i]);
}

return fileNames;
}

protected void buttonUpload_Click(object sender, System.EventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

string fileName = Path.Combine(Server.MapPath("~/uploads"), FileUpload1.FileName);
if (File.Exists(fileName))
File.Delete(fileName);
image.Save(fileName);

float imgWidth = image.PhysicalDimension.Width;
float imgHeight = image.PhysicalDimension.Height;
float imgSize = imgHeight > imgWidth ? imgHeight : imgWidth;
float imgResize = imgSize <= 128 ? (float)1.0 : 128 / imgSize;
imgWidth *= imgResize; imgHeight *= imgResize;
System.Drawing.Image thumb = image.GetThumbnailImage((int)imgWidth, (int)imgHeight, delegate() { return false; }, (IntPtr)0);

fileName = Path.Combine(
Server.MapPath("~/uploads"),
string.Format("{0}_th{1}",
Path.GetFileNameWithoutExtension(FileUpload1.FileName),
Path.GetExtension(FileUpload1.FileName)
)
);
if (File.Exists(fileName))
File.Delete(fileName);

thumb.Save(fileName);

UploadedFiles.DataBind();
}
protected void UploadedFiles_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
e.Cancel = true;
string fileName = ((HyperLink)UploadedFiles.Rows[e.RowIndex].FindControl("FileLink")).Text;
fileName = Path.Combine(Server.MapPath("~/uploads"), fileName);
File.Delete(fileName);
UploadedFiles.DataBind();
}
}

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment