
You may have seen many complex programs regarding uploading a file ,but in this post ,I will show you a very simple program for uploading a file .
This program is written using C# and Visual Studio 2008.
So Lets get started...................................................................
Fire up visual studio and open a new ASP.NET website
In this webpage add a FileUpload control from toolbox and a button.
Your webpage should look like the above image....................................
At the uploadbutton_click event Write the following code
protected void uploadbutton_Click(object sender, EventArgs e)
{
string strFileName = FileUpload1.PostedFile.FileName;\\Gets the wholepath of the file
string c = System.IO.Path.GetFileName(strFileName);
\\Gets the filename from the whole pathname
FileUpload1.PostedFile.SaveAs("C:\\images\\" + c);
\\ Saves the file in the desired directory (Instead of "C:\\images \\" ,Give the path where
you want to save the file.
Response.write("File uploaded successfully");
}
The above three line code is enough to upload a file,isnt it easy.
But if you want some extra information about the file being uploaded then you can use the following code
string filesize=FileUpload1.PostedFile.ContentLength.ToString();
\\ Gets the size of the file
string Content=FileUpload1.PostedFile.ContentType;
\\Gets the content type of file whether the file is an image or text
Using this additional code you can make your website more safe by restricting the kind of content being uploaded to the web server.
And the most Important thing
try testing this code on a seperate hard drive first before using it directly on your web server or on your Computers primary Hard drive ..................
No comments:
Post a Comment