Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. IO;
/// <Summary>
/// Summary description for uploadfile
/// </Summary>
Public class uploadfile
{
Private string [] allowfiletype; // allowed file types
Private double filelength; // allowed file size (KB)
Private string savepath; // file storage path
Private string SaveFile; // name of the uploaded file
Private string error; // stores the error message
Private string fileextesion; // File Upload Extension
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "allfiletype"> allowed file types, separated by "," </param>
/// <Param name = "filelength"> file size </param>
/// <Param name = "savepath"> Save path </param>
Public uploadfile (string allfiletype, double filelength, string savepath)
{
Char [] sp = {','};
Allowfiletype = allfiletype. Split (SP );
Filelength = filelength * 1024;
Savepath = savepath;
}
/// <Summary>
/// Return the generated file name
/// </Summary>
Public String filename
{
Get
{
Return SaveFile;
}
}
/// <Summary>
/// Error message returned
/// </Summary>
Public String errormessage
{
Get
{
Return Error;
}
}
/// <Summary>
/// Generate a file name based on savepath
/// </Summary>
/// <Returns> </returns>
Private string makefilename (string filetype, string filename)
{
String file = This. savepath "\" datetime. Now. tostring ("yymmddhhmmss") filename;
While (file. exists (File ))
{
File = This. savepath "\" datetime. Now. tostring ("yymmddhhmmss") filename;
}
Return file;
}
/// <Summary>
/// Check the file type
/// </Summary>
/// <Param name = "fileex"> mime content </param>
/// <Returns> </returns>
Private bool checkfileext (string fileex)
{
Bool result = false;
For (INT I = 0; I <this. allowfiletype. length; I)
{
If (fileex. indexof (this. allowfiletype [I]. tolower ()>-1)
{
Result = true;
Break;
}
}
Return result;
}
Public bool upload (system. Web. UI. webcontrols. fileupload file)
{
Bool result = true;
Try
{
// View the object Length
If (file. postedfile. contentlength> (this. filelength ))
{
This. Error = "the file size exceeds the permitted range! ";
Return false;
}
String filename = path. getfilename (file. postedfile. filename );
This. fileextesion = path. getextension (filename );
If (! Checkfileext (this. fileextesion. tolower ()))
{
This. Error = "file type" This. fileextesion "not allowed! ";
Return false;
}
// Get the file name to save
String upfile = This. makefilename (this. fileextesion, filename );
// Save the file
File. postedfile. saveas (upfile );
// Returns the file name.
This. SaveFile = path. getfilename (upfile );
}
Catch (exception E)
{
Result = false;
This. Error = E. message;
}
Return result;
}
}