Uploading images via .NET
Previously, adding the ability to upload images via ASP (with sizing, thumbnail features, etc.) would have required the use of an external component. With the advent of .NET, the ability to handle images can be done easily and freely through the use of the Bitmap and Image classes.
In this tutorial, we will be going through the steps of creating a simple web form in which you can upload an image file, and the form will verify whether it�s a JPEG file, whether there are duplicate files already (and rename your uploaded file if necessary), and create a thumbnail of the file uploaded.
This tutorial already assumes a basic knowledge of .NET Web Forms and C#.
By the way, some credit goes to Konstantin Vasserman for his code on uploading. If you need to upload the image into a DB, then look at his article.
- Create a new web application project.
- Open up the web form.
- Add a File field from the HTML tab onto your form, and convert it into a server control. In this example, the file field will be named filUpload.
(To convert any HTML tag into a server control, right click on it and select Run As Server Control.)
- Switch to HTML view and add/alter the enctype attribute of the form tag to multipart/form-data.
Example: enctype="multipart/form-data"
- Add a Web Form Button onto the form, and name it btnUpload.
- Add a folder called /images to the web application.
- Add a Web Form Image onto the form, and name it imgPicture. Adjust the width to 160 and height to 120.
- Add a Label called lblOutput. This will return any errors if the upload happens to fail.
- In the btnUpload Click event, add the following code.
(If you want to analyze the code in detail below, it's better to copy and paste into the VS.NET IDE since some of the lines are long.)
private void btnUpload_Click(object sender, System.EventArgs e)
{
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;
sSavePath = "images/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;
if (filUpload.PostedFile != null)
{
HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Text = "No file was uploaded.";
return;
}
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Text = "The file must have an extension of JPG";
return;
}
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData,0,nFileLen);
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData,0, myData.Length);
newFile.Close();
System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}
System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
imgPicture.ImageUrl = sSavePath + sThumbFile;
lblOutput.Text = "File uploaded successfully!";
myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}
}
public bool ThumbnailCallback()
{
return false;
}
- Run the webpage, and test with JPG files and other files to test the error-checking mechanism.
- If you have any problems/suggestions, please leave a message below. :-)