Upload File Z in ASP. NET 2.0

Source: Internet
Author: User
Upload File Z in ASP. NET 2.0

Transferred from:

Bill evjen
Reuters

Applicable:

Microsoft ASP. Network 2.0
Microsoft Visual Web Developer 2005 express Edition

Abstract:Learn how to use the newly added Microsoft ASP. NET 2.0FileuploadServer Control.

Content on this page
Introduction
Fileupload Server Control example
Summary

Introduction

Web applications have been generated since Microsoft ASP. NET 1.0 was introduced.ProgramThese methods can upload files to the host server. This is done by usingFile FieldHTML server control implementation. I have written an article on how to effectively use this control in ASP. NET Applications on msdnArticle. This article will introduce the File Upload process again, but does not use the File field control. I will show you how to effectively use the newFileuploadServer Control.

This article introduces youFileuploadServer Control, but can still be used in applicationsFile FieldControl. Note that this is very important.

Back to Top

Fileupload Server Control example

In ASP. NET 1.XUsed inFile FieldYou must take some additional steps to make everything work in an orderly manner. For exampleEnctype = "multipart/form-Data"Add to the page<Form>Element. New in ASP. NET 2.0FileuploadThe server control makes uploading files to the host server as simple as possible.

Finally, you try to allow<Input type = "file">Mark for programming. This tag is used with file data in an HTML form. In the past, when using traditional ASP (ASP 3.0 or earlier), many programmers used third-party components to upload files from the client to the server. Now, you can upload data through. Net and the new control. Listing 1 shows how to useFileuploadControl to upload files to the server.

NoteMicrosoft Visual Basic and C # format examples are provided.Code.

Listing 1. Using the fileupload control to upload files to the server

Visual Basic

<% @ Page Language = "VB" %> <SCRIPT runat = "server"> protected sub button#click (byval sender as object, _ byval e as system. eventargs) If fileupload1.hasfile then try fileupload1.saveas ("C: \ uploads \" & _ fileupload1.filename) label1.text = "file name:" & _ fileupload1.postedfile. filename & "<br>" & _ "file size:" & _ fileupload1.postedfile. contentlength & "kb <br>" & _ "content type:" & _ fileupload1.postedfile. contenttype catch ex as exception label1.text = "error:" & Ex. message. tostring () end try else label1.text = "You have not specified a file. "End if end sub </SCRIPT> <HTML xmlns =" http://www.w3.org/1999/xHTML "> 

C #

<% @ Page Language = "C #" %> <SCRIPT runat = "server"> protected void button#click (Object sender, eventargs e) {If (fileupload1.hasfile) try {fileupload1.saveas ("C :\\ uploads \" + fileupload1.filename); label1.text = "file name:" + fileupload1.postedfile. filename + "<br>" + fileupload1.postedfile. contentlength + "kb <br>" + "content type:" + fileupload1.postedfile. contenttype;} catch (exception ex) {label1.text = "error:" + ex. message. tostring ();} else {label1.text = "You have not specified a file. ";}} </SCRIPT> <HTML xmlns = "http://www.w3.org/1999/xHTML"> 

Run this page. If you seeSource code, You will notice some problems. Listing 2 lists the source code.

Listing 2. source code generated by the fileupload Control

    upload files    
   
   
    


The first thing to note is thatFileuploadThe control is located on this page, so ASP. NET 2.0 adds the correspondingEnctypeProperty to replace<Form>Element. You will also notice that,FileuploadThe control is converted to an html<Input type = "file">Element.

After the page in Listing 1 is running, you can select a file and upload it to the server by clicking the Upload File button on the page. For this example, we need to review some important things to understand all the steps required to implement this operation. To make the example in Listing 1 take effect, you must make the target folder on the server writable to the account used by ASP. NET to save the file to the specified folder.

If you believe that your ASP. NET account cannot write the desired folder, you only need to open Microsoft Windows Explorer and locate the folder to add this permission. Right-click the folder (in this example, the uploads folder) and selectProperties. InPropertiesIn the dialog box, clickSecurityTab, make sure that the list contains the ASP. NET Machine Account, which has the appropriate permissions to write data to the disk (see figure 1 ).

Figure 1. view the Security Tab Of the uploads folder

If ASP. NET machine account is not displayed on the Security tab, clickAddIn the text area, enter ASPnet (no deadline) to add the Account, as shown in figure 2.

Figure 2. Add the ASP. NET machine account to the folder security definition

ClickOKTo add ASP. NET machine accounts to the list. Make sure that the account has the appropriate permissions, and then clickOKIn this way, you are ready.

The submit button on this page will triggerButton#clickEvent occurs. This event uploads a file and then displays a message. by publishing information about the uploaded file, you can see whether the upload is successful. If the upload fails, this page displays an error message describing the cause of the upload failure.

Convert yourself<Input type = "file">MarkedFileuploadThe browser automatically places a browse button next to the text field on the ASP. NET page. This happens without any programming. When an end user clicks the Browse button, the user can browse the local file system to find the file to be uploaded to the server. 3. Click Open to put the file name and path of the file into the text field.

Figure 3. Select a file

Solve the file size limit

You may not be aware of this, but there is a limit on the size of the files that can be uploaded using this technology. By defaultFileuploadThe maximum size of files uploaded to the server is 4 MB. You cannot upload any content that exceeds this limit.

However, the important thing about. NET is that it usually provides a way to circumvent the limitation. You can change the default settings in use. To change the size limit, you can. config. comments file (in c: \ windows \ Microsoft. net \ framework \ v2.0.50727 \ config ASP.. NET 2.0 is found in the configuration folder) or the web. make some changes in the config file.

In the Web. config. Comments file, find a file named<Executiontimeout>As follows:

 
<Httpruntime executiontimeout = "110" maxrequestlength = "4096" bytes = "80" bytes = "false" minfreethreads = "8" minlocalrequestfreethreads = "4" bytes = "5000" enablekerneloutputcache =" true "enableversionheader =" true "encoding =" true "enable =" true "shutdowntimeout =" 90 "delaynotifnotiftimeout =" 5 "waitchangenotification =" 0 "maxwaitchangenotification =" 0 "enableheaderchecking =" true "sendcachecontrolheader =" true "apartmentthreading =" false "/>

Many operations are performed on this node, but the setting of the file size isMaxrequestlengthAttribute. By default, this attribute is set4096Kilobytes (KB ). You only need to change this value to increase the file size that can be uploaded to the server. If you want to allow uploading 10 MB of files to the serverMaxrequestlengthSet the value11264This means that the application allows uploading files up to 11000 kb to the server.

If you modify the settings in the web. config. Comments file, the settings are applied to all applications on the server. If you want to apply the setting only to the application in use, apply the node to the Web. config file of the application to overwrite all the settings in the web. config. Comments file. Make sure that the node is in the configuration file.<System. Web>Between Nodes.

Another setting related to the size limit of uploaded files is to assign<Httpruntime>NodeExecutiontimeoutAttribute Value.

AssignedExecutiontimeoutThe attribute value is the number of uploads allowed before ASP. NET is disabled. This value andMaxrequestlengthValue.

One drawback of increasing the size of files that can be uploaded is that hackers attack the server by sending a large number of requests. To avoid this situation, you can reduce the size of the files that can be uploaded. Otherwise, you may find hundreds or even thousands of 10 MB requests to access your server.

The client verifies the types of files that can be uploaded.

There are several methods to control the file types uploaded to the server. Unfortunately, there is no perfect way to prevent others from uploading malicious files. However, you can take steps to make it easier for end users to upload files.

A good method is to use the ASP. NET validation control provided free of charge by ASP. NET. These controls enable you to check the regular expression of the file being uploaded to see if the file extension is in the column that allows upload.

This method is mandatory on the client. Therefore, this is an ideal choice for browsers that allow verification controls on the client. If the signature is not your allowed signature, the file cannot be uploaded to the server. Listing 3 shows an example of using the verification control to complete the task.

NoteThe usage of the verification control is not described here. For a complete explanation of the verification controls and how to use them on the ASP. NET page, see validating ASP. NET Server controls.

Listing 3. Use the verification control to restrict the file types uploaded to the server

<Asp: fileupload id = "fileupload1" runat = "server"/> <br/> <asp: button id = "button1" runat = "server" onclick = "button#click" text = "Upload File"/> <br/> <asp: label id = "label1" runat = "server"> </ASP: Label> <asp: regularexpressionvalidator id = "regularexpressionvalidator1" runat = "server" errormessage = "only MP3, m3u or MPEG files are allowed! "Validationexpression =" ^ ([A-Za-Z] :) | (\\{ 2} \ W +) \$ ?) (\ W [\ W]. *) condition (items |. MP3 |. MPEG |. MPEG |. m3U |. m3u) ___ fckpd ___ 4 quot; controltovalidate = "fileupload1"> </ASP: regularexpressionvalidator> <br/> <asp: requiredfieldvalidator id = "requiredfieldvalidator1" runat = "server" errormessage = "this is a required field! "Controltovalidate =" fileupload1 "> </ASP: requiredfieldvalidator>

This simple ASP. NET page uses verification controls so that end users can only upload. MP3,. MPEG, or. m3u files to the server. If the file type is not the preceding optional file typeValidationThe control throws an exception to the screen. 4.

Figure 4. Verify the file type using the verification control

For files uploaded to the server, useValidationA widget is not an effective method to control it. Changing the file extension of a file is not too difficult, so the extension will be accepted and uploaded to the server, so as to avoid this simple security model.

Added Server File type verification

You just saw an easy way to add some ASP. NET authentication server controls to the ASP. NET page to verify the file extension on the client (in text format. Now let's take a look at how to perform similar operations on the server. See Figure 4.

Listing 4. Check the file type on the server

Visual Basic

Protected sub button#click (byval sender as object, _ byval e as system. eventargs) If fileupload1.hasfile then dim fileext as string fileext = system. io. path. getextension (fileupload1.filename) if (fileext = ". MP3 ") Then try fileupload1.saveas (" C: \ uploads \ "& _ fileupload1.filename) label1.text =" file name: "& _ fileupload1.postedfile. filename & "& _" file size: "& _ fileupload1.postedfile. cont Entlength & "kb" & _ "content type:" & _ fileupload1.postedfile. contenttype catch ex as exception label1.text = "error:" & Ex. message. tostring () end try else label1.text = "only. MP3 files allowed! "End if else label1.text =" You have not specified a file. "End if end sub

C #

Protected void button#click (Object sender, eventargs e) {If (fileupload1.hasfile) {string fileext = system. io. path. getextension (fileupload1.filename); If (fileext = ". MP3 ") {try {fileupload1.saveas (" C :\\ uploads \ "+ fileupload1.filename); label1.text =" file name: "+ fileupload1.postedfile. filename + "" + fileupload1.postedfile. contentlength + "kb" + "content type:" + fileupload1.postedfil E. contenttype;} catch (exception ex) {label1.text = "error:" + ex. Message. tostring () ;}} else {label1.text = "only. MP3 files allowed! ";}} Else {label1.text =" You have not specified a file .";}}

NowSystem. Io. PathUse in namespaceGetextensionYou can perform the same operation. For end users, simply changing the file extension to a valid name and uploading the changed file to the host server does not affect the function. Note that this is important.

Upload multiple files at the same time

So far, there have been several good examples of how to upload files to the server at no extra cost. Now, let's see how to upload multiple files from one page to the server.

Microsoft. NET Framework does not have any built-in functions that allow you to upload multiple files from an ASP. NET page. However, you only need a small amount of work to use. Net 1.XTo complete the task.

The method isSystem. IoClass to the ASP. NET page, and then useHttpfilecollectionClass capture throughRequestAll files sent by the object. This method enables you to upload the required quantity of files from a page.

If needed, you can process eachFileuploadControl, as shown in listing 5.

Listing 5. Processing each fileupload control separately

Visual Basic

 
If fileupload1.hasfile then 'handle fileend ifif fileupload2.hasfile then' handle fileend if

C #

If (fileupload1.hasfile) {// handle file} If (fileupload2.hasfile) {// handle file}

This method is valid, but this situation may exist: You must useHttpfilecollectionClass to process files, especially when processing the dynamically generated Server Control List.

In this case, you can generate an ASP. NET page with threeFileuploadControl and a submit button (using the button control ). After you click the submit button and the file is published to the server, the hidden code saves the file to a specific location on the server. After saving the file, the published file information is displayed on the ASP. NET page (see Listing 6 ).

Listing 6. Uploading multiple files to the server

Visual Basic

Protected sub button#click (byval sender as object, _ byval e as system. eventargs) dim filepath as string = "C: \ uploads" dim uploadedfiles as httpfilecollection = request. files dim I as integer = 0 do until I = uploadedfiles. count dim userpostedfile as httppostedfile = uploadedfiles (I) Try if (userpostedfile. contentlength> 0) Then label1.text + = "file #" & (I + 1) & "" label1.text + = "file content type:" & _ userpostedfile. contenttype & "" label1.text + = "file size:" & _ userpostedfile. contentlength & "kb" label1.text + = "file name:" & _ userpostedfile. filename & "" userpostedfile. saveas (filepath & "\" & _ system. io. path. getfilename (userpostedfile. filename) label1.text + = "location where saved:" & _ filepath & "\" & _ system. io. path. getfilename (userpostedfile. filename) & _ "" end if catch ex as exception label1.text + = "error:" & Ex. message end try I + = 1 loopend sub

C #

Protected void button#click (Object sender, eventargs e) {string filepath = "C: \ uploads"; httpfilecollection uploadedfiles = request. files; For (INT I = 0; I <uploadedfiles. count; I ++) {httppostedfile userpostedfile = uploadedfiles [I]; try {If (userpostedfile. contentlength> 0) {label1.text + = "file #" + (I + 1) + ""; label1.text + = "file content type:" + userpostedfile. contenttype + ""; label1.text + = "file size:" + userpostedfile. contentlength + "kb"; label1.text + = "file name:" + userpostedfile. filename + ""; userpostedfile. saveas (filepath + "\" + system. io. path. getfilename (userpostedfile. filename); label1.text + = "location where saved:" + filepath + "\" + system. io. path. getfilename (userpostedfile. filename) + "" ;}} catch (exception ex) {label1.text + = "error:" + ex. message ;}}}

The end user can select up to four files, and then click the upload files button, this button will initializeButton#clickEvent. UseHttpfilecollectionClass andRequest. FilesAttribute allows you to control all files uploaded from this page. When these files are in this status, you can perform any operations on them. In this example, check the file attributes and output them to the screen. Finally, these files are saved to the uploads folder in the root directory of the server. Result 5 of this operation is shown.

Figure 5. Upload four files on an ASP. NET page to the server at a time

You may have noticed that, in this example, the status of the input text box is not saved by sending back. You can see this in Figure 5. In ASP. NET, the status of the input text box of the file cannot be saved, because this may cause security risks.

Back to Top

Summary

Provided by ASP. NETFileuploadServer Control is a powerful control, which is very difficult to implement in the era of Active Server Pages 3.0. This new feature allows end users to upload one or more files to the server. Remember, you can control the file size by using settings in the web. config. Comments or web. config file.

About the author

Bill evjen is A. NET technology and. netCommunityActive supporters of the learning program. He isReutersIs an international news and financial services company located in St. Louis, Missouri. Bill isInternational. Net Association (ineta)The Creator and Executive Director of the organization, which has more than 100,000 members worldwide. Bill is also a author and speaker. His books includeASP. NET professional secrets,XML Web Services for ASP. NET,Web Services enhancementsAndVisual Basic. Net Bible(AllWileyPublishing ).

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.