在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
By Bill Evjen
Feburary 2004 Applies to:
Summary: Learn how to use the Microsoft ASP.NET File Field control to allow your end-users to upload one or more files to your server. (16 printed pages) ContentsIntroduction
IntroductionMicrosoft® ASP.NET Web Forms are all about communicating with an end-user to abstract what information you need to from them depending on the service administered. In many cases with Web Forms, it is usually simply textual data that is collected and stored. However, there are many cases where you are going to need more than simple textual data; you may want your users to upload files to the server. For instance, your application can have a document library that is shared with all users. There are plenty of examples, but invariably you will need this ability to upload any type of document for storage, or to have your application take action upon the document once it is uploaded. In any case, ASP.NET provides you with a simple ability to upload documents to the server with just a little work on your part. This article describes how to use the File Field control for uploading documents to your Web server. Looking Closely at the File Field ControlThe File Field control uses the It is important to note that this control is called the File Field control in all versions of Microsoft Visual Studio® .NET, while in the ASP.NET Web Matrix, this control is called the FileUpload control. In both cases, you will find the control in the HTML section of the Toolbox. The File Field control allows access to program the HTML Note The sample code is provided in both Microsoft Visual Basic® (VB) and C#. Listing 1. Uploading files to the server using the File Field control VB <%@ Page Language="VB" %> <script runat="server"> Sub SubmitButton_Click(Source As Object, e As EventArgs) If Not (File1.PostedFile Is Nothing) Then Try File1.PostedFile.SaveAs("C:\Uploads\uploadedfile.txt") Span1.InnerHtml = "Upload Successful!" Catch ex As Exception Span1.InnerHtml = "Error saving file <b>C:\\" & _ File1.Value & "</b><br>" & ex.ToString() End Try End If End Sub </script> <html> <head> </head> <body> <form runat="server" enctype="multipart/form-data"> Select a file to upload:<br /> <input type="file" > <p> <input type="submit" value="Upload File" OnServerClick="SubmitButton_Click"> <p> <span /> </form> </body> </html> C# <%@ Page Language="C#" %> <script runat="server"> void SubmitButton_Click(Object sender, EventArgs e) { if (File1.PostedFile != null) { try { File1.PostedFile.SaveAs("C:\\Uploads\\uploadedfile.txt"); Span1.InnerHtml = "Upload Successful!"; } catch (Exception ex) { Span1.InnerHtml = "Error saving file <b>C:\\" + File1.Value + "</b><br>" + ex.ToString(); } } } </script> <html> <head> </head> <body> <form runat="server" enctype="multipart/form-data"> Select a file to upload:<br /> <input type="file" > <p> <input type="submit" value="Upload File" OnServerClick="SubmitButton_Click"> <p> <span /> </form> </body> </html> When the page from Listing 1 is run, you can select a file and upload it to the server by clicking the Upload File button on the page. This is a great feature that ASP 3.0 programmers always wished for. Now it is here in .NET! With only a few lines of code, it is easy to upload any type of files to the server. There are some important items we should go over for this example so you understand all the needed pieces to make this work. First, for the example in Listing 1 to work, you have to make the destination folder on the server writeable for the account used by ASP.NET so the file can be saved to the specified folder. If you think your ASP.NET account is not enabled to write to the folder you want, simply open up Microsoft Windows® Explorer and navigate to the folder to which you want to add this permission. Right-click on the folder (in this case, the Uploads folder), and then select Properties. In the Properties dialog box, click on the Security tab and make sure the ASP.NET Machine Account is included in the list and has the proper permissions to write to disk (see Figure 1). Figure 1. Looking at the Security tab of the Uploads folder If you don't see the ASP.NET Machine Account under the Security tab, you can add it by clicking the Add button and entering ASPNET (without the period) in the text area, as illustrated in Figure 2. Figure 2. Adding the ASP.NET Machine Account to the folder security definition Click OK to add the ASP.NET Machine Account to the list. From here, make sure you give this account the proper permissions; then click OK and you are ready to go. Looking at the code from Listing 1, you might notice some really important things right away. First, the The Submit button on the page causes an By using the Figure 3. Choosing a file Working Around File Size LimitationsYou may not realize it, but there is a limit to the size of a file that can be uploaded using this technique. By default, the maximum size of a file to be uploaded to the server using the File Field control is around 4MB. You cannot upload anything that is larger than this limit. One of the great things about .NET, however, is that it usually provides a way around limitations. You can usually change the default settings that are in place. To change this size limit, you make some changes in either the In the <httpRuntime executionTimeout="90" maxRequestLength="4096" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" /> A lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the Making this change in the Another setting involved in the size limitation of files to be uploaded is the value given to the The value given the One negative with increasing the size of a file that can be uploaded is that there are hackers out there who attack servers by throwing a large number of requests at them. To guard against this, you can actually decrease the size of the files that are allowed to be uploaded; otherwise, you may find hundreds or even thousands of 10 MB requests hitting your server. Controlling Uploaded File TypesThere are a several methods you can use to control the types of files that are uploaded to the server. Unfortunately, there is no bullet-proof method to protect you from someone uploading files that would be considered malicious. You can take a few steps, however, to make this process of allowing end users to upload files a little more manageable. One nice method you can employ is to use the ASP.NET validation controls that are provided for free with ASP.NET. These controls enable you to do a regular-expression check upon the file that is being uploaded to see if the extension of the file is one you permit to be uploaded. This is ideal for browsers that allow client-side use of the validation controls because it forces the checking to be done on the client; the file is not uploaded to the server if the signature isn't one you allow. Listing 2 shows you an example of using validation controls to accomplish this task. Note The use of validation controls is not explained here. Take a look at Validating ASP.NET Server Controls for a complete explanation of validation controls and how to use them in your ASP.NET pages. Listing 2: Using validation controls to restrict the types of files uploaded to the server VB <%@ Page Language="VB" %> <script runat="server"> Sub SubmitButton_Click(Source As Object, e As EventArgs) If Not (File1.PostedFile Is Nothing) Then Try File1.PostedFile.SaveAs("C:\Uploads\uploadedfile.txt") Span1.InnerHtml = "Upload Successful!" Catch ex As Exception Span1.InnerHtml = "Error saving file <b>C:\\" & _ File1.Value & "</b><br>" & ex.ToString() End Try End If End Sub </script> <html> <head> </head> <body> <form enctype="multipart/form-data" runat="server"> <input /> <p> <input runat="Server" onserverclick="SubmitButton_Click" /> </p> <span /> <p> <asp:RegularExpressionValidator ErrorMessage="Only mp3, m3u or mpeg files are allowed!" ValidationExpression="^(([a-zA- Z]:)|(\\{2}\w+)\$?)(\\(\w[\w ].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" ControlToValidate="File1"> </asp:RegularExpressionValidator> <br /> <asp:RequiredFieldValidator ErrorMessage="This is a required field!" ControlToValidate="File1"> </asp:RequiredFieldValidator> </p> </form> </body> </html> C# <%@ Page Language="C#" %> <script runat="server"> void SubmitButton_Click(Object sender, EventArgs e) { if (File1.PostedFile != null) { try { File1.PostedFile.SaveAs("C:\\Uploads\\uploadedfile.txt"); Span1.InnerHtml = "Upload Successful!"; } catch (Exception ex) { Span1.InnerHtml = "Error saving file <b>C:\\" + File1.Value + "</b><br>" + ex.ToString(); } } } </script> <html> <head> </head> <body> <form enctype="multipart/form-data" runat="server"> <input /> <p> <input runat="Server" onserverclick="SubmitButton_Click" /> </p> <span /> <p> <asp:RegularExpressionValidator ErrorMessage="Only mp3, m3u or mpeg files are allowed!" ValidationExpression="^(([a-zA- Z]:)|(\\{2}\w+)\$?)(\\(\w[\w ].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" ControlToValidate="File1"> </asp:RegularExpressionValidator> <br /> <asp:RequiredFieldValidator ErrorMessage="This is a required field!" ControlToValidate="File1"> </asp:RequiredFieldValidator> </p> </form> </body> </html> This simple ASP.NET page uses validation controls so that the end user can only upload Figure 4. Validating the file type using validation controls Using validation controls is not a foolproof way of controlling the files that are uploaded to the server. It wouldn't be too hard for someone to change the file extension of a file so it would be accepted and uploaded to the server, thereby bypassing this simple security model. Uploading Multiple Files at the Same TimeSo far, you have seen some good examples of how to upload a file to the server without much hassle. Now let's take a look at how to upload multiple files to the server from a single page. No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from a single ASP.NET page. With a little work, however, you can easily accomplish this task. One trick is to import the For this example, you can build an ASP.NET page that has four file-input boxes and one Submit button. After the user clicks the Submit button and the files are posted to the server, the code behind takes the files and saves them to a specific location on the server. After the files are saved, the file information that was posted is displayed in the ASP.NET page (see Listing 3). Listing 3: Uploading multiple files to the server VB <%@ Import Namespace="System.IO" %> <%@ Page Language="VB" %> <script runat="server"> Sub SubmitButton_Click(Source As Object, e As 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 Span1.InnerHtml += "<u>File #" & (i+1) & "</u><br>" Span1.InnerHtml += "File Content Type: " & _ userPostedFile.ContentType & "<br>" Span1.InnerHtml += "File Size: " & _ userPostedFile.ContentLength & "kb<br>" Span1.InnerHtml += "File Name: " & _ userPostedFile.FileName & "<br>" userPostedFile.SaveAs(filepath & "\" & _ Path.GetFileName(userPostedFile.FileName)) Span1.InnerHtml += "Location where saved: " & _ filepath & "\" & _ Path.GetFileName(userPostedFile.FileName) & _ "<p>" End If Catch ex As Exception Span1.InnerHtml += "Error:<br>" & ex.Message End Try i += 1 Loop End Sub </script> <html> <head> </head> <body> <form enctype="multipart/form-data" runat="server"> <p> Select File1:<br /> <input /> <br /> Select File2:<br /> <input /> <br /> Select File3:<br /> <input /> <br /> Select File4:<br /> <input /> </p> <p> <input runat="Server" onserverclick="SubmitButton_Click" /> <br /> </p> <span ></span> </form> </body> </html> C# <%@ Import Namespace="System.IO" %> <%@ Page Language="C#" %> <script runat="server"> protected void SubmitButton_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 ) { Span1.InnerHtml += "<u>File #" + (i+1) + "</u><br>"; Span1.InnerHtml += "File Content Type: " + userPostedFile.ContentType + "<br>"; Span1.InnerHtml += "File Size: " + userPostedFile.ContentLength + "kb<br>"; Span1.InnerHtml += "File Name: " + userPostedFile.FileName + "<br>"; userPostedFile.SaveAs(filepath + "\\" + Path.GetFileName(userPostedFile.FileName)); Span1.InnerHtml += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>"; } } catch (Exception Ex) { Span1.InnerText += "Error: <br>" + Ex.Message; } } } </script> <html> <head> </head> <body> <form enctype="multipart/form-data" runat="server"> <p> Select File1:<br /> <input /> <br /> Select File2:<br /> <input /> <br /> Select File3:<br /> <input /> <br /> Select File4:<br /> <input /> </p> <p> <input runat="Server" onserverclick="SubmitButton_Click" /> <br /> </p> <span ></span> </form> </body> </html> The end user can select up to four files and click the Upload Files button, which initializes the Figure 5. Uploading four files at once to the server from a single ASP.NET page As you may have noticed, one interesting point about this example is that the states of the file input text boxes are not saved with the postback. You can see this in Figure 5. In ASP.NET, the state of the file-input text boxes cannot be saved because doing so might pose a security risk. ConclusionThe File Field control provided by ASP.NET is a powerful control that was quite difficult to achieve in the days of Active Server Pages 3.0. This new capability allows your end-users to upload one or more files to your server. Remember, you can control the size of the files that are uploaded by working with settings in either the |
请发表评论