Fileupload file upload and Path Problems in asp.net

Source: Internet
Author: User

The FileUpload control displays a text box control and a browse button, allowing you to select a file on the client and upload it to the Web server. You can enter the complete path of the file on the Local Computer in the control text box.

You can enter the complete path of the file on the Local Computer (for example,C: MyFilestest. Txt) To specify the file to be uploaded. You can also click the Browse button and then select a file in the select file dialog box.


After you select the file to upload,FileUploadThe control does not automatically save the file to the server. You must explicitly provide a control or mechanism for users to submit specified files. For example, you can click a button to upload a file. To save the code written in a specified file, call the SaveAs method, which saves the file content to the specified path on the server. Generally, it is called in the event processing method that triggers events that are sent back to the server.SaveAsMethod.


During file upload, the file data is part of the page request, uploaded and cached to the server's memory, and then written to the server's physical hard disk.
 

Several public read-only attributes commonly used by the FileUpload Control

 

Name Return type Description
FileContent Stream Returns a Stream object pointing to the uploaded file.
FileName String Returns the name of the file to be uploaded on the client, excluding the path information.
HasFile Boolean Returns a Boolean value indicating whether the FileUpload control contains a file.
PostedFile HttpPostedFile Obtain an HttpPostedFile object related to the uploaded file. You can use this object to obtain the attributes of the uploaded file. The following table lists the read-only attributes it exposes.

 

HttpPostedFile attributes
 

Name Return type Description
ContentLength Integer Returns the size of the uploaded file in bytes.
ContentType String Returns the MIME content type of the uploaded file.
FileName String The fully qualified name of the returned file on the client.
InputStream Stream Returns a stream object pointing to the uploaded file.

 

Note the following three aspects::


1. Check whether the file is included


Before callingSaveAsThe HasFile attribute is used for verification before saving the file to the server.FileUploadThe control does contain files. IfHasFileReturnTrue, CallSaveAsMethod. If it returnsFalseIs 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 ifFileUploadThe control is empty,PostedFileProperty 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 httpRuntime ElementMaxRequestLengthTo upload larger files.

The related nodes are as follows:


<System. web>
<HttpRuntime maxRequestLength = "40690" executionTimeout = "6000"/>
</System. web>

MaxRequestLength indicates the maximum value of a file to be uploaded, and executionTimeout indicates the number of uploads allowed before ASP. NET is disabled.

To increase the maximum file size allowed by the entire application, SetMaxRequestLengthAttribute. To increase the maximum file size allowed by the specified page, SetLocationElementMaxRequestLengthAttribute.
When uploading a large file, you may receive the following error message:


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 in the <processModel> Configuration section.MemoryLimitDefault attribute value. 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.
 

You can access and upload files in three ways:


1. Use the FileBytes attribute. This attribute stores the uploaded file data in a byte array and traverses the array to understand the content of the uploaded file in bytes.


2. Use the FileContent attribute. You can call this attribute to obtain a Stream object pointing to the uploaded file. You can use this attribute to read uploaded file data and use the FileBytes attribute to display the file content.


3. Use the PostedFile attribute. You can call this attribute to obtain an HttpPostedFile object related to the uploaded file. You can use this object to obtain information related to the uploaded file. For example, you can call the ContentLength of the HttpPostedFile object to obtain the size of the uploaded file, call the ContentType attribute of the HttpPostedFile object to obtain the type of the uploaded file, and call the FileName attribute of the HttpPostedFile object, you can obtain the complete path of the uploaded file on the client (only the file name can be obtained by calling the FileName attribute of the FileUpload control ).


The FileUpload control uploads simple instances:

The Code is as follows: Copy code

// Drag a FileUpload control and a button control at the front end.
 
<Asp: FileUpload ID = "FileUpload1" runat = "server"/> <br/>
<Asp: Button ID = "Button1" runat = "server" OnClick = "button#click" Text = "Button"/>

// Background
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;

Public partial class Manage_News_upload: System. Web. UI. Page
...{
Protected void Page_Load (object sender, EventArgs e)
...{

}
Protected void button#click (object sender, EventArgs e)
...{
If (FileUpload1.HasFile)
...{
String fileExrensio = System. IO. Path. GetExtension (FileUpload1.FileName). ToLower (); // convert ToLower to lowercase
String FileType = FileUpload1.PostedFile. ContentType;
String UploadURL = Server. MapPath ("~ /Upload/"); // The uploaded directory
If (FileType = "image/bmp" | FileType = "image/gif" | FileType = "image/jpeg" | FileType = "image/jpg" | FileType = "image/png ") // determine the file type
...{

Try
...{
If (! System. IO. Directory. Exists (UploadURL) // you can check whether a folder already Exists.
...{
System. IO. Directory. CreateDirectory (UploadURL); // create a folder
}

FileUpload1.PostedFile. SaveAs (UploadURL + FileUpload1.FileName );
}
Catch
...{
Response. Write ("failed ");
}
}
Else
...{
Response. Write ("format error ");
}
}
Else
Response. Write ("select a file ");
}
}

There are still many attributes that are not used in the above instance. You can add attributes as needed to determine and write the upload method that meets your project requirements.

Upload multiple files at a time

To upload multiple files at a time, we can process each file as a leaflet file. In addition, we can also use the HttpFileCollection class to capture all the files sent from the Request object, then process each file separately.

Instance

 

The Code is as follows: Copy code
Protected void button#click (object sender, EventArgs e)
...{
String filepath = Server. MapPath ("upload") + "\\";
HttpFileCollection uploadFiles = Request. Files;
For (int I = 0; I <uploadFiles. Count; I ++)
...{
HttpPostedFile postedFile = uploadFiles [I];
Try
...{
If (postedFile. ContentLength> 0)
...{
Label1.Text + = "file #" + (I + 1) + ":" + System. IO. Path. GetFileName (postedFile. FileName) + "<br/> ";
PostedFile. SaveAs (filepath + System. IO. Path. GetFileName (postedFile. FileName ));
}
}
Catch (Exception Ex)
...{
Label1.Text + = "error:" + Ex. Message;
}
}
}

FileUpload File Upload Path Problems

Scenario:

The files we upload are generally stored in the virtual directory of the server, rather than the place where the program runs. Let's take a look at the following code.

The Code is as follows: Copy code

Protected void btnUpload_Click (object sender, EventArgs e)
{
If (FileUpload1.HasFile)
{
String fileExt = System. IO. Path. GetExtension (FileUpload1.FileName );
If (fileExt = ". jpg" | fileExt = ". gif ")
{
Try
{
FileUpload1.SaveAs (Server. MapPath ("/ScenicImg") + "\" + FileUpload1.FileName );
Label1.Text = "client path:" + FileUpload1.PostedFile. FileName + "<br>" +
"File name:" + System. IO. Path. GetFileName (FileUpload1.FileName) + "<br>" +
"File Extension:" + System. IO. Path. GetExtension (FileUpload1.FileName) + "<br>" +
"File size:" + FileUpload1.PostedFile. ContentLength + "KB <br>" +
"File MIME type:" + FileUpload1.PostedFile. ContentType + "<br>" +
"Save path:" + Server. MapPath ("/ScenicImg") + "\" + FileUpload1.FileName;
}
Catch (Exception ex)
{
Label1.Text = "error:" + ex. Message. ToString ();
}
}
Else
{
Label1.Text = "only jpg and gif files can be uploaded! ";
}
}
Else
{
Label1.Text = "no file to upload is selected! ";
}
}

Note that "/" in server. mappath here indicates the main directory of the program, so that you can find the virtual directory.

If this/is not added, the path is mapped to the place where the program runs.

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.