Ajax File Upload Code
<%@ Import namespace= "System.IO"%>
<%@ page language= "C #" debug= "true"%>
<title>ajax asp.net upload file, </title>
<script language= "C #" runat= "Server" >
This is called the "Upload" button ID pressed
public void UploadFile (object sender, EventArgs E)
{
Check that the upload file is not empty
if (myfile.postedfile!=null)
{
String nam = MyFile.PostedFile.FileName;
Gets the last "." in the filename (enclosing path). The index
int i= Nam. LastIndexOf (".");
Get file name extension
String Newext =nam. Substring (i);
Here I automatically name the file according to the date and file size to ensure that the filename is not duplicated
DateTime now = DateTime.Now;
String Newname=now. Dayofyear.tostring () +myfile.postedfile.contentlength.tostring ();
Save the file to the directory you want, this is the upload directory under the IIS root directory. You can change.
Note: I use Server.MapPath () to take the absolute directory of the current file. In asp.net "\" must be replaced with "\"
MyFile.PostedFile.SaveAs (Server.MapPath ("img/" +newname+newext));
MyFile.PostedFile.SaveAs (Server.MapPath ("img/" +));
Get the related attributes of this file: file name, file type, file size
FName. Text=myfile.postedfile.filename;
Fenc. Text=myfile.postedfile.contenttype;
Fsize. Text=myfile.postedfile.contentlength.tostring ();
Fsize. Text = System.IO.Path.GetFileName (NAM);
String localname = System.IO.Path.GetFileName (Myfile.value);
string path = MyFile.PostedFile.FileName;
MyFile.PostedFile.SaveAs (Server.MapPath ("img/" + localname));
FName. Text = LocalName;
Fenc. Text = System.IO.Path.GetExtension (Path);
FilePath. Text = path;
Filebytes. Text = MyFile.PostedFile.ContentLength.ToString ();
}
}
</script>
<body>
<center>
<form id=" Uploderform "method=" POST "action=" Fileupload.aspx "enctype=" multipart/form-data runat= "Server"
<table border= "1" cellspacing= "2" cellpadding= "2"
<tr> <td> <tr>
<td>
<input type= "file" id= "MyFile" runat= "Server" Name= "MyFile"
</td>
</tr>
<tr><td>
<input type= "button" value= "Upload onserverclick=" uploadfile "runat=" Server "id=" Button1 "Name=" "Button1"
</td></tr>
</table>
</form>
<br>
< Br>
<table border= "1" cellspacing= "2"
<tr><td><b> Documents </b></td>
<td> </td>
</tr>
<tr>
<td> filename:</td>
<TD ><asp:label id= "fname" text= "" runat= "Server"/></td></tr>
<tr>
<td> File Type:</td>
<td><asp:label id= "Fenc" runat= "Server"/></td></tr>
<tr>
<td> file path:</td>
<td><asp:label id= "filepath" runat= "Server"/></td></tr>
<tr>
<td> File Size:</td>
<td><asp:label id= "filebytes" runat= "Server"/></td></tr>
</table>
<br>
<br>
<br>
</center>
</body>