1. Interface arrangement
This part of the functionality involved in the main control two: one is (ID) WebFile file field control, to browse the upload files path, the other is (ID) for the Btnupload upload button, click it to complete the file upload.
2, Code implementation
Double-click the Btnupload button in the design panel to add event handling for it, as shown in the following code:
Copy Code code as follows:
private void Btnupload_click (object sender, System.EventArgs e)
{
if (webfile.postedfile.filename== "")
{
info.text= "Please select the file to upload first";
Return
}
Try
{
Char[] Spliter = {' \ '};
string [] FileName = WebFile.PostedFile.FileName.Split (spliter,10);
String fullpath = Currentpath + @ "\" + filename[filename.length-1];
Generate full file name
WebFile.PostedFile.SaveAs (FullPath); Save File
Loaddir (Currentpath); Reload the current directory
}
Catch
{
info.text= "Upload file failed, please contact the Administrator";
}
}
The first thing to determine is whether the user has selected the file to upload, which can be obtained by WebFile.PostedFile.FileName properties. What you need to note is that WebFile is a file field control object that belongs to the HtmlInputFile class, and the Htmlinputfile.postedfile method is used to obtain access to the uploaded file from the client.
After the user has chosen the file to upload, it is necessary to set the path to upload. First you get the file name of the file. Because the user provides a client full path, the split () method needs to be split by the "//" delimiter, and the result is stored in an array. such as: "C://userdir//chapter1//ch1.doc" can be divided into four parts, the last part (array last) is exactly the name of the file required. In the above program, Filename[filename.length-1] is the name of the file that the user uploaded.
The upload path can be uploaded, where the Postedfile.saveas () method is used. When the upload is complete, call the Loaddir () method to display the file name you just uploaded.
When you click the Browse button at run time, a dialog box appears as shown in Figure 16-5. When the file is selected, click OK to complete the file upload work.
Figure "Browse" files to upload