Sun
Sun

Reputation: 4718

Warn user that the file size is too big using a FileUpload control in ASP.Net

I'm using a FileUpload control to allow users to upload a file to an SQL database.

I have a button which I use to load the selected file via C# code.

However if the file size is of certain size the upload fail. I have a break point on the C# code which never gets hit when the size is to large but it does when the file size is OK. This is where I would have put the check but the break point doesn't get hit!??!

What's the best way to implement this? Should I use JavaScript?

The C# code behind the button is below but it never get fired:

protected void buttonAddDocumentType_Click(object sender, EventArgs e)
{
    int size = fileUploadDocument.PostedFile.ContentLength;

    //This is where I'd like to perform the file size check 

    byte[] fileData = new byte[size];

    fileUploadDocument.PostedFile.InputStream.Read(fileData, 0, size);

    WebDataAccess.InsertDocument(Int32.Parse(Request.QueryString["ID"].ToString()), Int32.Parse(comboDocumentTypes.SelectedValue), fileUploadDocument.FileName, fileUploadDocument.PostedFile.ContentType,
                fileUploadDocument.FileBytes.Count(), fileData);

    comboDocumentTypes.SelectedIndex = -1;
}

I'm using ASP.Net 4.0

Thanks in advance.

Upvotes: 1

Views: 5629

Answers (2)

Peter Hahndorf
Peter Hahndorf

Reputation: 11222

First, if you have valid uploads bigger then 4MB, you need to increase the maxRequestLength in web.config,

Say you accept files up to 10MB, change it to 16MB, now you handle any files bigger than 10MB in your code and anything bigger then 16MB is rejected by the asp.net runtime. You don't want to change the maxRequestLength to a very high number, because than people could attack your server with huge files.

<system.web><httpRuntime maxRequestLength="16384" />

You can check the

fileImageControl.PostedFile.InputStream.Length 

property before you are calling:

fileImageControl.PostedFile.SaveAs

I always save any uploaded files into a temp directory, and run some checks on them before saving them into their final location. You can also mark them as 'downloaded from the internet', so Windows treats them accordingly (but that doesn't work if you save them into a database).

Upvotes: 0

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20775

Asp.Net has an upper limit for file uploads. You can configure this limit in web.config and validate this range before file upload event is started.

It's not possible to use code to catch this error, as it occurs before any code is started.

Upvotes: 1

Related Questions