C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » ASP.NET WebForms »

Upload Image and define size


Posted Date: 18 Apr 2009    Resource Type: Code Snippets    Category: ASP.NET WebForms
Author: nisarMember Level: Gold    
Rating: 1 out of 5Points: 10



Hey, I am presenting a code how to upload an image + check valid extension + create thumbnail + define thumbnail width and height
OK now come to detail, I only allow the .jpg extension, that you can find in the code with comments, you change your required extension, I also check either file has contents are not by simply add if statement

if (nFileLen == 0)
{
Your Message
}

You can change your thumbnail width and height by changing the variable value from 400 hundred to your required integer

intThumbWidth = 400;
intThumbHeight = 400;

In exception you can find the code how to delete a file, you can also make a function to delete a file, and pass the path of server and the file will be deleted from server
Keep in mind I am saving both file in folder, mean thumbnail and the original file, if you want then you can only save the thumbnail
You will find more comments in code, but if you have any problem regarding to this code then please feel free to ask

I am not inserting the code of aspx file, so please note that in aspx file you need just two controls, upload control(ID=filUpload) and label control(ID=lblOutput), if you want to execute this function on clink event of button then you also need to button control and execute UploadImage() function in button click.

public void UploadImage()
{
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;

// Set constant values

sSavePath = "~/Images/";
sThumbExtension = "_thumb";
intThumbWidth = 400;
intThumbHeight = 400;

// If file field isn’t empty

if (filUpload.PostedFile != null)
{
// Check file size (mustn’t be 0)

HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Text = "No file was uploaded.";
return;
}

// Check file extension (must be JPG)

if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Text = "The file must have an extension of JPG";
return;
}

// Read file into a data stream

byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);

// Make sure a duplicate file doesn’t exist. If it does, keep on appending an

// incremental numeric until it is unique

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";
}

// Save the stream to disk

System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();

// Check whether the file is really a JPEG by opening it

System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

// If jpg file is a jpeg, create a thumbnail filename that is unique.

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";
}

// Save thumbnail and output it onto the webpage

System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
//imgPicture.ImageUrl = sSavePath + sThumbFile;

// Displaying success information

lblOutput.Text = "File uploaded successfully!";
string CompletePath = "~/Images/" + sThumbFile; //Get folder and FilePath

myThumbnail.Dispose();
myBitmap.Dispose();
// DeleteHDFile();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file

lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}
}

public bool ThumbnailCallback()
{
return false;
}




Responses

Author: rangasamy    15 Oct 2009Member Level: Bronze   Points : 0



Author: Robin Thomas    18 Nov 2009Member Level: Bronze   Points : 0
Thanks nisar for the wonderful code

It workss...............


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Upload image  .  Create image thumbnail  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Calling Asp.NET webservice from Javascript
Previous Resource: Returns the qualified web application virtual path
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET WebForms


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use