Asp tutorial. net upload and download files using server controls
Step 1: Select Upload File. Determine the file format in each two steps. Step 3: Specify the storage directory. Step 4: Save the file.
If you don't talk nonsense about serving food directly:
<Asp: fileupload id = "fileupload" style = "border: solid 1px # a5d0f3;" width = "300px" runat = "server"/>
<Asp: button id = "btnupload" runat = "server" text = "Upload File" onclick = "btnupload_click" onclientclick = "return fun_checktype ();"/>
<Script type = "text/Webpage effects">
Function fun_checktype (){
Var filename = document. getelementbyid ("fileupload"). value;
If (filename = ""){
Alert ("select the uploaded file! ");
Return false;
}
Var seat = filename. lastindexof (".");
Var extension = filename. substring (seat). tolowercase ();
// Set the format
Var allowed = [". jpg ",". gif ",". png ",". bmp ",". jpeg ",". SQL ",". txt ",". doc ",". xls "];
For (var I = 0; I <allowed. length; I ++ ){
If (! (Allowed [I]! = Extension )){
Return true;
}
}
Alert ("not supported" + extension + "format! ");
Return false;
}
</Script>
The source code is very clean and simple, so I will not explain it more. Note that the Click Event of the button client is onclientclick.
Now, the dish has been served, and the main course is started.
Protected void btnupload_click (object sender, eventargs e)
{
// Specify the file storage directory. Here, there is a condition Server
If (! System. io. directory. exists (server. mappath ("~ /Filelist/files ")))
System. io. directory. createdirectory (server. mappath ("~ /Filelist/files "));
// Save the file
Fileupload. postedfile. saveas (server. mappath ("~ /Filelist/files/"+ fileupload. filename ));
Scriptmanager. registerstartups Tutorial example (this. page, this. gettype (), "", "alert ('uploaded successfully');", true );
}
Of course, there will be some logic judgment and exception capturing in the upload event. In order to achieve a clear effect, they will be saved here.
Add the following code to delete a file:
// Delete files on the server
System. io. file. delete (server. mappath ("~ /Filelist/files/xxx.doc "));