Kash
Kash

Reputation: 245

Apply file upload size restriction on server side in asp.net C#

I am applying file upload size restriction, that user can't upload files more than 30 MB, and give him message if he exceeds the limit. I am using following code.

if (fileUpload.HasFile)
            {
                if (fileUpload.PostedFile.ContentLength < 30 * 1024 * 1024) // 30 MB
                {
                    if (fileUpload.FileName != null && fileUpload.FileName != "")
                    {
                        UploadFile(fileUpload, "flv,mp3", out videoFileName, out uploadError);
                        if (uploadError != "")
                        {
                            lblMessage.Visible = true;
                            lblMessage.Text = uploadError;
                            return false;
                        }
                    }
                }
                else
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "File size exceeds the Limits. Please try uploading smaller size file.";
                    return false;
                }
            }

This code works fine in Visual Studio, but when I deploy the application on iis, it doesn't give me any message if I give more then 30 MB file, and directly upload the file.

where I am doing wrong.

Regards, Kash

Upvotes: 1

Views: 3371

Answers (4)

Vijay EK
Vijay EK

Reputation: 184

You can check the size of the uploaded file only after the upload is complete. Check this link http://forums.asp.net/t/55127.aspx

Upvotes: 1

Justin Wignall
Justin Wignall

Reputation: 3510

Have you used the standard maxRequestLength config property? It may well be that it's not suitable for your needs but it will work better in not utilising resources one the file limit is reached.

For an explanantion about how to handle the error see A better way of handling maxRequestLength exceptions

<system.web>
  <httpRuntime  maxRequestLength="31457280" executionTimeout="360"/>
</system.web>

Upvotes: 2

JayOnDotNet
JayOnDotNet

Reputation: 398

When running under IIS7 You can set the file upload size limit like this in web.config file

<system.webServer>    
<security> 
<requestFiltering>                 
<requestLimits maxAllowedContentLength="10485760"/>   
</requestFiltering> 
</security> </system.webServer>

Upvotes: 2

Simon Wang
Simon Wang

Reputation: 2943

with such a code, it looks it works that way, I mean you code will execute only if the full content been post to the server. You need some extra work to verify the size on client side, or use some third party plugins like uploadify

Upvotes: 1

Related Questions