Namespace Wmj
{
Public class MyUpload
{
Private System. Web. HttpPostedFile postedFile = null;
Private string savePath = "";
Private string extension = "";
Private int fileLength = 0;
// Display the parameters used by this component
Public string Help
{
Get {
String helpstring;
Helpstring = "<font size = 3> MyUpload myUpload = new MyUpload (); // constructor ";
Helpstring + = "myUpload. PostedFile = file1.PostedFile; // set the file to be uploaded ";
Helpstring + = "myUpload. SavePath = \" e :\\\ "; // sets the path to be uploaded to the server. The default value is c :\\";
Helpstring + = "myUpload. FileLength = 100; // sets the maximum length of the uploaded file, in k. The default value is 1 k ";
Helpstring + = "myUpload. Extension = \" doc \ "; sets the Extension of the uploaded file. Default: txt ";
Helpstring + = "label1.Text = myUpload. Upload (); // start the Upload and display the Upload result. </font> ";
Helpstring + = "<font size = 3 color = red> Design By WengMingJun 2001-12-12 All Right Reserved! </Font> ";
Return helpstring;
}
}
Public System. Web. HttpPostedFile PostedFile
{
Get
{
Return postedFile;
}
Set
{
PostedFile = value;
}
}
Public string SavePath
{
Get
{
If (savePath! = "") Return savePath;
Return "c :\\";
}
Set
{
SavePath = value;
}
}
Public int FileLength
{
Get
{
If (fileLength! = 0) return fileLength;
Return 1024;
}
Set
{
FileLength = value * 1024;
}
}
Public string Extension
{
Get
{
If (extension! = "") Return extension;
Return "txt ";
}
Set
{
Extension = value;
}
}
Public string PathToName (string path)
{
Int pos = path. LastIndexOf ("\\");
Return path. Substring (pos + 1 );
}
Public string Upload ()
{
If (PostedFile! = Null)
{
Try {
String fileName = PathToName (PostedFile. FileName );
If (! FileName. EndsWith (Extension) return "You must select" + Extension + "file! ";
If (PostedFile. ContentLength> FileLength) return "File too big! ";
PostedFile. SaveAs (SavePath + fileName );
Return "Upload File Successfully! ";
}
Catch (System. Exception exc)
{Return exc. Message ;}
}
Return "Please select a file to upload! ";
}
}
}
Use csc/target: Library Wmj. cs to compile it into a dll for multiple future calls
Call example
<% @ Page language = "C #" runat = "server" %>
<% @ Import namespace = "Wmj" %>
<Script language = "C #" runat = "server">
Void Upload (object sender, EventArgs e)
{
MyUpload myUpload = new MyUpload ();
// Label1.Text = myUpload. Help;
MyUpload. PostedFile = file1.PostedFile;
MyUpload. SavePath = "e :\\";
MyUpload. FileLength = 100;
Label1.Text = myUpload. Upload ();
}
</Script>
<Form enctype = "multipart/form-data" runat = "server">
<Input type = "file" id = "file1" runat = "server"/>
<Asp: Button id = "button1" Text = "Upload" OnClick = "Upload" runat = "server"/>
<Asp: Label id = "label1" runat = "server"/>
</Form>