ASP tutorial. NET uploads and downloads files using server controls
The first step, select Upload file. Every two steps to determine the file format. The third step, specify the storage directory, step fourth, save the file.
No more nonsense. Direct dishes:
<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/web Effects" >
function Fun_checktype () {
var filename = document.getElementById ("FileUpload"). Value;
if (filename = = "") {
Alert ("Please select the uploaded file!") ");
return false;
}
var seat = Filename.lastindexof (".");
var extension = filename.substring (seat). toLowerCase ();
Set 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 ("does not support + extension +" format!) ");
return false;
}
</script>
The source is very clean and simple, do not explain more, need to pay attention to is the button client Click event: OnClientClick
OK, the cold dish is already on the table, now start the main course.
protected void Btnupload_click (object sender, EventArgs e)
{
Specifies the file storage directory, which has a condition server
if (!system.io.directory.exists (Server.MapPath ("~/filelist/files"))
System.io.directory.createdirectory (Server.MapPath ("~/filelist/files"));
Save File
Fileupload.postedfile.saveas (Server.MapPath ("~/filelist/files/" + fileupload.filename));
Scriptmanager.registerstartups Tutorial Cript (This.page, This.gettype (), "", "alert (' upload succeeded ');", true);
}
Of course there will be some logical judgments and exception captures in the upload event, in order to achieve a clear effect, here they are omitted.
Add a deletion file code:
Delete files on the server
System.io.file.delete (Server.MapPath ("~/filelist/files/xxx.doc"));