Asp.net File Upload
Asp.net file upload control is used to upload file on server. At server side you get file content in terms of byte array. You also get filename and other details. First you need to locate the location of file on server using Server.MapPath method.
Here we will see how to upload any file on server and filter the file using it's extension. Filtration of file is based on it's extension and not the content of the file.
FileName method of File upload control returns file name. If you want to store the file on server using different name, you don't need to refer the uploaded file name. Simply, give your own file name with extension.
For example Server.MapPath("uploads") returns physical path of the folder on server. and System.IO.Path.GetExtension("xxx.txt") method returns ".txt" string as an extension.
Asp.net File upload control example.
public partial class FileUploadDemo : System.Web.UI.Page
protected void Button1_Click(object sender, EventArgs e)
string filePath = Server.MapPath("uploads");
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs( filePath + @"/" + fileName );
Label1.Text = "File has been successfully uploaded...";
To see uploaded file on server, refresh the uploads folder.
We have created this folder on root of the web site.
Note: On production server make sure that you have write permission on folder.
Remember: Handle exception using try catch blocks to avoid crash.
The example shown above stores the file at physical location
on server (on HDD drive folder).
You may want to store the file on MS SQL server. To do that,
you can get the file in bytes. FileBytes is a property of file upload control, which returns file content array of bytes.
You can use this array of bytes to store the file content on server.
Here is an example of upload image file using file upload control and store it in MS SQL server.
Refer: Asp.net Upload Image To Database.
All examples are very simple and easy to understand.
Summery: The important methods and properties of file upload control are
1. FileBytes, it returns content of file as an array of bytes.
2. FileName, This property of file upload control is used to get name of file.
3. SaveAs, Method of File Upload control stores the file at given location on server. It accepts file path (Physical path location).
4. Server.MapPath is used to get physical path from virtual path.
5. Make sure you have Right permission before uploading the file on server.
6. To get extension of file use GetExtension static method of System.IO.Path class.