您的位置:首页 > 编程语言 > VB

AsyncFileUpload File Type and File Size Validation using VB.NET

2010-12-15 15:34 4143 查看
Table of Contents:
AsyncFileUpload File Type and File Size Validation using VB.NET

Server side validation: Validating File Types and File Sizes

AsyncFileUpload File Type and File Size Validation using VB.NET

(Page 1 of 2 )

If you're just started using the AsyncFileUpload AJAX web control, you'll be pleased to hear it can do more than just upload files. There are also ways to validate the file types and sizes it uploads. This article will show you how, using both client and server side validation.
You might have read the introductory tutorial on the AsyncFileUpload web control ("AsyncFileUpload Updatepanel Example in ASP.NET AJAX using VB.NET") as part of the AJAX Control Toolkit in ASP.NET 3.5. However, the sample project in that tutorial is plain and simple. It does not validate file types and file sizes, and it does not provide output as to the status of the file upload.

In real web applications involving file uploading, there is a need to:

Validate the file type uploaded to the server.

Validate the uploaded file size.

Return results and status about the uploaded file. This tells the user whether the uploading is ongoing, completed or has encountered an error.

AsyncFileUpload is an AJAX web control for uploading files without post back or with partial post back. This tutorial will introduce some validation techniques, mainly for the file types and sizes of the uploaded files.

To do this effectively, the application should do both client and server side validation. The client side validation will use JavaScript and the server side validation will use VB.NET.

Getting Started: Creating the Original AsyncFileUpload Project

To get started, you will use the original project files, which will be implemented in this tutorial with validation. You can download it here:http://www.dotnetdevelopment.net/tutorials/asyncfileupload_projectoriginal.zip

After downloading, right click on it and click “Extract here.” Copy the asyncfileupload_projectoriginal folder to your ASP.NET local website folders.

Navigate into the folder and open Default.aspx.vb with Visual Web Developer. Edit the file upload path to reflect your own path. You need to revise this line and assign your own file upload path:

Dim fileuploadpath1 As String = "E:aspdotnetprojectsasyncfileupload_projectoriginalupload"

Launch your Visual Web Developer project. Under “Recent Projects” click “Open,” and under “Open Web Site” look for “asyncfileupload_projectoriginal,” and then click “Open.”

Once you see the Default.aspx script, view the project using a web browser (File -> View in Browser). Try uploading a file larger than 4 MB -- an MP3 file, for example. You might notice that you will receive an error: “Unhandled Exception: Access is Denied.” This is because the default maximum allowable file size for uploading is 4 MB. To increase this limit to 20 MB (for example), you need to add this line in web.config:

<location path="default.aspx">
<system.web>
<httpRuntime executionTimeout="110" maxRequestLength="20000" />
</system.web>
</location>

You need to add those lines just above <system.web>. See screen shot:



After making these changes, go to File -> Save all. Go to Default.aspx and view the project again in the browser. Try uploading large files (greater than 4 MB but less than 20 MB); they will be successfully uploaded to the /upload/ folder in your project.

Adding Throbber to Display Uploading Progress

Before you can validate file types/sizes, it would be a good practice to add an uploading progress indicator by using a throbber. To do this,

1. Add a ThrobberID="throbber" property in AsyncFileUupload:

<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnUploadedComplete ="UploadFile1" ThrobberID="throbber" /><br />

2. Add an ASP.NET label control outputting the throbber to the browser:

<asp:Label runat="server" ID="throbber" Style="display: none;">
<img alt="" src="throbber/progress.gif" />
</asp:Label>

You can download the sample throbber folder with progress.gif indicator here:http://www.dotnetdevelopment.net/tutorials/throbber.zip

Unzip it (Right click-> Extract here) and copy the throbber folder to the asyncfileupload_projectoriginal project folder.

3. Test the throbber by viewing the project again in the browser. Try uploading large files greater than 10 MB but less than 20 MB; you will see the progress indicator working.

Client side validation: Validating File Types and File Sizes

The first step is to validate the file type and file sizes. The steps are as follows:

1. Add ASP.NET labels to display upload status, upload file name, upload file size and content type. Add the following code next to throbber:

<br />
<div style="display: none; font-family:Courier; width: 600px" id="dvFileInfo">
Upload Status: <asp:Label ID="uploadsuccess" ForeColor="Blue" runat="server" /><br />
Uploaded FileName: <asp:Label ID="uploadfiledisplay" ForeColor="Blue" runat="server" /><br />
Uploaded File Size : <asp:Label ID="uploadfilesizedisplay" ForeColor="Blue" runat="server" /><br />
Uploaded Content Type :<asp:Label ID="uploadcontenttypedisplay" ForeColor="Blue" runat="server" /><br />
</div>

2. Add ASP.NET labels to display upload related errors, such as wrong file type or inappropriate file sizes. Add the following code next to the code above and before </ContentTemplate>.

<div style="display: none; font-family:Courier; width: 800px" id="dvFileErrorInfo">
Upload Status: <asp:Label ID="uploaderror" ForeColor="Red" runat="server" /><br />
</div>

3. Add an OnClientUploadComplete="uploadComplete" in the AsyncFileUpload control. This is the JavaScript function that will execute after the user completely selects the file for uploading.

<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnUploadedComplete ="UploadFile1" OnClientUploadComplete="uploadComplete" ThrobberID="throbber" /><br />

4. The next step is to add and create the uploadComplete JavaScript function to do the client validation for file types and file sizes. Add the following code between <head>…</head> section and just below <title></title>

<script type="text/javascript">
function uploadComplete(sender, args) {
try {
var fileExtension = args.get_fileName();
var mp3 = fileExtension.indexOf('.mp3');
var filesizeuploaded = parseInt(args.get_length());
if (mp3 > 0 && (filesizeuploaded < 5000000)) {
$get("dvFileInfo").style.display = 'block';
$get("dvFileErrorInfo").style.display = 'none';
$get("<%=uploadsuccess.ClientID%>").innerHTML = "File Uploaded Successfully";
$get("<%=uploadfiledisplay.ClientID%>").innerHTML = args.get_fileName();
$get("<%=uploadfilesizedisplay.ClientID%>").innerHTML = args.get_length();
$get("<%=uploadcontenttypedisplay.ClientID%>").innerHTML = args.get_contentType();
}
else {
$get("dvFileErrorInfo").style.display = 'block';
$get("<%=uploaderror.ClientID%>").innerHTML = "File NOT uploaded.Allowed file extension are mp3 file type only and should be less than 4.5 MB.";
$get("dvFileInfo").style.display = 'none';
return;
}
}
catch (e) {
alert(e.message);
}
}

</script>

Code Discussion

The user will browse the file to be uploaded to the server. After the user has completed this step, asyncfileupload automatically uploads the file and triggers the JavaScript function “uploadComplete” as defined in OnClientUploadComplete="uploadComplete."

The first thing the function does is get the file name and assign it to the fileExtension JavaScript variable. Then the string “.mp3” will be searched for in the file name, using the JavaScript indexOf function, and the results will be assigned to the mp3 variable.

Also, the file size of the uploaded file is computed using parseInt(args.get_length()); function in JavaScript.

The most important part of the JavaScript function above is the condition:

if (mp3 > 0 && (filesizeuploaded < 5000000)) {

This condition will check to see if the file extension is mp3 and the file size uploaded is less than 5 MB. If this condition is true, it will return the following success values back to the client browser (courtesy of the ASP.NET labels declared previously):

Upload Status (which is a success)

Uploaded file name

Uploaded file size

Uploaded file type

However, if the condition is false, it will return an error to the user stating that the file type and file sizes are not correct.

AsyncFileUpload File Type and File Size Validation using VB.NET - Server side validation: Validating File Types and File Sizes

(Page 2 of 2 )

This is the most important part, because this will do the actual job of blocking the files to be uploaded/saved to the upload folder. If there is no server validation, any user can bypass client side validation and still upload files to your upload path.

Below is the complete VB.NET script, which you will copy and paste into Default.aspx.vb:

Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub UploadFile1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim fileuploadreceive1 As String = AsyncFileUpload1.PostedFile.FileName
Dim uploadedfilesize As Integer = AsyncFileUpload1.PostedFile.ContentLength
Dim filename1 As String = Path.GetFileName(fileuploadreceive1)
If ((Path.GetExtension(fileuploadreceive1).Contains(".mp3")) And (uploadedfilesize < 5000000)) Then
Dim fileuploadpath1 As String = "E:aspdotnetprojectsasyncfileupload_projectoriginalupload"
AsyncFileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath1, filename1))
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = DateTime.Now
End Sub
End Class

Code Discussion

The first thing the script will do is import the namespaces required for all of the functions. An example of namespaces includes the System.Data, System.Configuration, etc. Next it will execute the VB.NET function named UploadFile1. This is the function that will execute as defined in the AsyncFileUpload OnUploadedComplete ="UploadFile1" property.

The following declaration statements will get the posted file to the server, and also get the filename and the file size.

Dim fileuploadreceive1 As String = AsyncFileUpload1.PostedFile.FileName
Dim uploadedfilesize As Integer = AsyncFileUpload1.PostedFile.ContentLength
Dim filename1 As String = Path.GetFileName(fileuploadreceive1)

As with the client side validation, the most important part of the VB.NET script is the condition:

If ((Path.GetExtension(fileuploadreceive1).Contains(".mp3")) And (uploadedfilesize < 5000000))

This returns true if the file posted is an mp3 file (contains an mp3 file extension) and the file size is less than 5 MB. If this is true, the posted file will be saved to the defined path in your ASP.NET server:

Dim fileuploadpath1 As String = "E:aspdotnetprojectsasyncfileupload_projectupload"
AsyncFileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath1, filename1))

Go to File -> Save All, and then go to Default.aspx to view the completed project in the browser. Try uploading an MP3 file which is less than 5 MB and you will see a result similar to the one shown below:

<


The file will be successfully uploaded and saved to the upload path defined in the scripts. Also try uploading a file which is larger than than the 5 MB upload file size limit. You will see an error such as the one shown below:



The file will not be uploaded and saved to the upload path in your server.

You can download the revised/completed project here:http://www.dotnetdevelopment.net/tutorials/asyncfileupload_projectoriginal_revised.zip

Some portion of the code discussed in this tutorial are improvised based on the scripts provided here:

http://weblogs.asp.net/manojkdotnet/archive/2009/10/16/asynfileupload-control-and-its-validation.aspx

http://yasserzaid.wordpress.com/2009/11/30/ajax-asynfile-upload-with-file-extension-validation/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: