This article will show you how you can restrict user to upload
file of a specific size in asp.net using c#.net on server side.
Some of my previous articles are as follows: Ajax
FileUpload Control In Asp.Net or Multiple FileUpload With Progress Example in
Asp.Net Using C#.Net, File
Upload in MVC3 By Using Razor, Multiple
File Upload With Asp.Net MVC C# and HTML5 | How to upload files to ASP.NET MVC
application, File
Upload with ASP.NET | How to Use FileUpload Control in ASP.Net Using
C#.Net,VB.Net | Upload File in Asp.net and Save in Folder, Restrict
User to Upload Only doc or .docx Using Fileupload in Asp.Net C#.Net.
For this article first we will create a new asp.net
application and add fileupload control and a button control.
<div>
<h2>
<asp:Label ID="lblmessage" runat="server" Style="color: #FF0000; font-size: small;"
Text=""></asp:Label>
</h2>
Upload File :<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
(allowed only max 2MB to upload) <br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
</div>
|
Now we will create the button click event by clicking on
button control. Now use the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UploadFileinAsp.net
{
public partial class _Default : System.Web.UI.Page
{
protected
void Page_Load(object
sender, EventArgs e)
{
}
protected
void Button1_Click(object
sender, EventArgs e)
{
if
(FileUpload1.HasFile)
{
/*1MB=1024KB*/
long
filesize = ((FileUpload1.PostedFile.ContentLength) / 1024) / 1024;
if
(filesize < 2)
{
string
filename = System.IO.Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/document/"
+ filename));
lblmessage.Text = "File uploaded successfully.";
}
else
{
lblmessage.Text = "You are allowed to upload more then 2MB.";
}
}
}
}
}
|
In above code we have get the uploaded file size by FileUpload1.PostedFile.ContentLength. After getting file size we converted the byte
into MB by dividing 1024. So we have done with code. Now run the page.
But before this we will make a configuration change. Add the
below setting in web.config.
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
|
Have a look of the file size we are going to upload whose
size is 4MB.
Now we will select the file click on browse button and click on upload .
Now have a look of the
file of size less than 2MB.
Now select file and click on upload.
Now click on upload after selecting file.
DOWNLOAD
0 comments:
Please let me know your view