Preliminary use of the FileUpload control:
1. Implement File Upload
Protected void btnSubmit_click (object sender, EventArgs e)
{
If (FileUpload1.HasFile = true)
{
String strErr = "";
// Obtain the size of the uploaded file
Int filesize = FileUpload1.PostedFile. ContentLength;
If (filesize> 1024*1024)
{
StrErr + = "the file size cannot exceed 1 MB \ n ";
}
If (strErr = "")
{
// Obtain the current path of the Server File
String path = Server. MapPath ("~ ");
// Save the uploaded file in the upload folder of the current path
FileUpload1.PostedFile. SaveAs (path + "\ upload \" + FileUpload1.FileName );
LblInfo. Text = "the file is saved successfully ";
}
}
Else
{
LblInfo. Text = "specify the file to be uploaded ";
}
}
2. restrict the types of uploaded files
// Get the file extension and convert it to lowercase
String fileExtension = System. IO. Path. GetExtension (FileUpload1.FileName). ToLower ();
// Only jpg and GIF images can be uploaded.
String [] allowExtension = {". jpg", ". gif", ". txt", ". xls "};
// Determine the type of the uploaded file www.2cto.com
For (int I = 0; I <allowExtension. Length; I ++)
{
If (fileExtension = allowExtension [I])
{
FileOk = true;
Break;
}
}
You can further use the FileUpload. PostedFile. ContentType attribute to determine the file type:
String fileContentType = FileUpload1.PostedFile. ContentType;
If (fileContentType = "image/bmp" | fileContentType = "image/gif" | fileContentType = "image/pjpeg ")
{
//-----
}
3. Name the uploaded file in time
String fileName = Server. MapPath ("~ ") +" \ Upload \ "+ DateTime. Now. ToString (" yyyyMMddHHmmss ") +". jpg ";
FileUpload1.SaveAs (fileName );
4. Upload large files
When using the FileUpload control in ASP. NET controls, you sometimes need to upload large files. By default, the maximum size of uploaded files is 4 MB. To upload a larger file, you can change two default settings in the configuration file: maxRequestLength and requestLengthDiskThreshold in httpRuntime. The former specifies the maximum size of the uploaded file, the latter sets the cache size, in KB.
For example:
<Configuration>
<System. web>
...
<HttpRuntime maxRequestLength = "10240" requestLengthDiskThreshold = "100"/>
...
</System. web>
</Configuration>
The preceding settings allow you to upload files up to 10 MB and change the cache threshold to kb.
However, if the setting is too large, a denial-of-service attack is caused by a large number of files being transferred to the server.
The cold Sand Island is lonely.
From Lonely sandcontinent