|
Last method allows files of any size to be uploaded by calling our UploadImage
method.
protected void UploadImageWithNoRestrictions(HttpPostedFile file)
{
if(IsImage(file))
{
UploadImage(file);
}
}
The last method is the method which actually uploads the image and creates a new resized
image ( thumbnail ) to be shown on the default.aspx page.
It first fetches the file name ( e.g. myimage.jpg ) from the complete path and file
name ( e.g. C:\SomeFolder\AnotherFolder\myimage.jpg ) of the uploaded image. It then saves
that image in the 'uploaded_images' folder on the server.
Next it creates a new Bitmap image from the existing image ( uploaded image )
with new width and height ( 150x150 px ). It then saves the new thumbnail image as well in the
'uploaded_images' folder by prepending the image name with 't__' e.g. t__myimage.jpg.
So after this method successfully returns, you have two images created in the 'uploaded_images'
folder. So for example if the uploaded image was myimage.jpg, then the two images that get
created will be myimage.jpg ( same uploaded image file ) and t__myimage.jpg ( the resized
thumbnail ).
Tip: Memorize and understand the code we have used to create a new resized image file. As
you will be using this code later on ( after all this is why you've read this article ).
protected void UploadImage(HttpPostedFile file)
{
string fileName = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);
string filePath = MapPath("uploaded_images/" + fileName);
file.SaveAs(filePath);
AppendMessage("<span style=\"color:green;\">File Uploaded...</span><br>");
using(System.Drawing.Image image =
System.Drawing.Image.FromStream(file.InputStream))
using(Bitmap bitmap = new Bitmap(image, ThumbnailWidth, ThumbnailHeight))
{
bitmap.Save(MapPath("uploaded_images/t__" + fileName), image.RawFormat);
AppendMessage("<span style=\"color:green;\">Thumbnail " +
" created...</span><br><br>");
}
}
This is how upload.aspx looks like on my system before we upload any file:
Screenshot: upload.aspx
And after we have uploaded a file:
Screenshot: upload.aspx
|