Example of uploading a file using the FileUpload control in Asp.net

Source: Internet
Author: User
Tags datetime exception handling file size file upload server memory
The code is as follows: Copy code
/// <Summary> use the FileUpload control to upload a file </summary>
/// <Param name = "page"> this </param>
/// <Param name = "path"> File storage directory. Example of relative path :"~ /UploadFile ", absolute path example:" E: UploadFile ". Tip: Use a slash in the web path and a backslash in the file system </param>
/// <Param name = "fu"> FileUpload </param>
/// <Param name = "checkFileName"> whether to check the file name. "true" indicates that duplicate file names are not allowed. "false" indicates renaming the file name with time. </param>
/// <Param name = "allowTypes"> specifies the file type and extension that can be uploaded, for example, "xls". If the file type is not limited, pass null. </param>
/// <Returns> absolute file path </returns>
        
Public static string UploadFileToServer (Page page, String path, FileUpload fu, Boolean checkFileName, params String [] allowTypes)
        { 
// Record file name
String fileName = fu. FileName;
// Select a file
If (string. IsNullOrEmpty (fileName ))
            { 
MsgBox. Alert (page, "select a file first! ");
Return null;
            } 
// Record file extension
String fileType = fileName. Substring (fileName. LastIndexOf ('.') + 1 );
// Determine whether the extension is allowed
Bool typeRight = false;
// Record the types of files that can be uploaded
String allowType = "";
// Specify the file type
If (allowTypes! = Null)
            { 
// Traverse the array of allowed file types
For (int I = 0; I <allowTypes. Length; I ++)
                { 
// If it has been judged as permitted, it will not be judged
If (! TypeRight)
                    { 
// Determine whether the extension size conversion meets the requirements
If (fileType = allowTypes [I] | fileType. ToLowerInvariant () = allowTypes [I] | fileType. ToUpperInvariant () = allowTypes [I])
                        { 
// Set to allow
TypeRight = true;
                        } 
                    } 
// Record the types of files that can be uploaded
AllowType + = "." + allowTypes [I] + "| ";
                } 
// Delete the last separator
AllowType = allowType. Remove (allowType. LastIndexOf ("| "));
            } 
// When the file type is not specified
Else
            { 
// Directly set to allow
TypeRight = true;
            } 
// Incorrect extension
If (! TypeRight)
            { 
// Indicates the file type that can be uploaded.
MsgBox. Alert (page, "the file format is incorrect. Select a file with the extension [" + allowType +! ");
Return null;
            } 
// Whether the file can be obtained normally
If (fu. PostedFile. ContentLength = 0)
            { 
MsgBox. Alert (page, "the selected file cannot be found. Please reselect it! ");
Return null;
            } 
 
// Absolute directory path
String dirRootPath = "";
// File path exception handling
Try
            { 
// If the path is relative
If (! Path. IsPathRooted (path ))
                { 
// Convert relative directory path to absolute path
DirRootPath = HttpContext. Current. Server. MapPath (@ "" + path + "/"). Trim ();
                } 
Else
                { 
// Save path
DirRootPath = path;
                } 
// Whether the file upload directory exists
DirectoryInfo dirInfo = new DirectoryInfo (dirRootPath );
If (! DirInfo. Exists)
                { 
// This directory is created if it does not exist.
DirInfo. Create ();
                } 
            } 
Catch (Exception pathError)
            { 
// Exception dialog box prompt
MsgBox. Alert (page, "error:" + pathError. Message );
Return null;
            } 
// The absolute path of the record file
String fileRootPath = "";
// When you need to check whether the file name is repeated
If (checkFileName)
            { 
// Absolute file path
FileRootPath = Path. Combine (dirRootPath, fileName );
// The file name already exists.
If (File. Exists (fileRootPath ))
                { 
// Rename
MsgBox. Alert (page, "a file with the same name already exists on the server. Modify the file name and try again! ");
Return null;
                } 
            } 
Else
            { 
// Rename the selected file by time
String newFileName = fileName. remove (fileName. lastIndexOf (". ") + DateTime. now. toString ("yyMMddHHmmss") + DateTime. now. millisecond. toString () + ". "+ fileType;
// Absolute file path
FileRootPath = Path. Combine (dirRootPath, newFileName );
            } 
// Upload to the server
Fu. SaveAs (fileRootPath );
 
// Returns the absolute path of the object.
Return fileRootPath;

Pay attention to the following three aspects::

1. Check whether the file is included

Before calling the SaveAs method to save the file to the server, use the HasFile attribute to verify that the FileUpload control does contain the file. If HasFile returns true, the SaveAs method is called. If false is returned, a message is displayed to the user indicating that the control does not contain files. Do not check the PostedFile attribute to determine whether the file to be uploaded exists, because this attribute contains 0 bytes by default. Therefore, even if the FileUpload control is empty, the PostedFile attribute returns a non-null value.

2. File upload size limit

By default, the size of the uploaded file is limited to 4096 KB (4 MB ). You can set the maxRequestLength attribute of the httpRuntime element to allow uploading larger files. To increase the maximum file size allowed by the entire application, set the maxRequestLength attribute in the Web. config file. To increase the maximum file size allowed by the specified page, set the maxRequestLength attribute in the location element in Web. config.
When uploading a large file, you may receive the following error message:
Aspnet_wp.exe (PID: 1520) was recycled because memory consumption exceeded 460 MB (60 percent of available RAM ).
The above information indicates that the size of the uploaded file cannot exceed 60% of the server memory size. Here, 60% is Web. The default configuration of the config file is the default value of the memoryLimit attribute in the <processModel> configuration section. It can be modified, but the larger the file to be uploaded, the smaller the chances of success. It is not recommended.

3. Write permission for the upload folder

Applications can obtain write access permissions in two ways. You can explicitly grant the write access permission to the directory where the uploaded files will be saved to the account used to run the application. You can also increase the level of trust granted to ASP. NET applications. To grant the application write access permission to the execution directory, you must grant the application the AspNetHostingPermission object and set its trust level to the value of AspNetHostingPermissionLevel. Medium. Increasing the level of trust can improve the application's access to server resources. Please note that this method is not safe, because if a malicious user controls the application, he or she can run the application with a higher level of trust. The best practice is to run ASP. NET applications in user context that only has the minimum privilege required to run the application.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.