How can I control file size in Upload control?

I have an Upload file control on my page and whould like to control that only small files will be uploaded to the server,  how can I do that? How can I control file extension ?

Thanks
nuritatAsked:
Who is Participating?
 
JayFromPepCommented:
Attached is a class that I use that does the same sort of thing.  I check the file type, but do not manipulate it.

However, you can craft whatever you would like and have it save the file in any way you would  like.

Now if you want to limit the files that they can even attempt to upload, that is a different story.  Because it is client side, you would need a client side language, like javascript.

See the Second code snippet....

You would use it like so....

<asp:FileUpload ID="FileUpload1" runat="server" onchange ="checkFileExtension(this);" />

protected void bUpload_Click(object sender, EventArgs e)
    {
        if (templateUpload.HasFile)
        {
            if (FileTypeCheck(templateUpload.FileName) == true)
            {
                _FileName = FileDateTime + ".csv";
                _FullPath = Server.MapPath("~") + "\\Mydir\\" + _FileName;
                _VirtualPath = "~/MyVirtDir/" + _FileName;
                templateUpload.SaveAs(@_FullPath);
                //Session.Add("fullpath", _FullPath);
                lStatus.Text = "Your file was uploaded and is now being processed.<br><br>You will be able to view the results of the upload below, prior to committing them to the database.";
                lStatus.Visible = true;
            }
            else
            {
                lStatus.Text = "You selected a file that is not a csv file.  You must select a csv file for uploading.";
                lStatus.Visible = true;
            }
        }
        else
        {
            lStatus.Text = "You must select a file before uploading.";
            lStatus.Visible = true;
        }
    }

Open in new window

function checkFileExtension(elem) {
        var filePath = elem.value;

        if(filePath.indexOf('.') == -1)
            return false;
        
        var validExtensions = new Array();
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
        //Add valid extentions in this array
        validExtensions[0] = 'doc';
        //validExtensions[1] = 'pdf';
    
        for(var i = 0; i < validExtensions.length; i++) {
            if(ext == validExtensions[i])
                return true;
        }

        alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
        return false;
    }

Open in new window

0
 
Andre412Commented:
To only take action when say less than 5MB

If UploadControl.PostedFile.ContentLength < 500000I Then
0
 
carlnorrbomCommented:
Hi,

Or if you want to limit the upload file size cross your site in one place you can simply do it in the httpRuntime section in the web.config by specifying maxRequestLength:
<httpRuntime 
    maxRequestLength="5120"
    executionTimeout="3600"
  />

Open in new window


In this example it's limited to 5MB (5x1024KB).

/Carl.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
SokratesCommented:
I see both answers dont give you solution on all your questions.

1)control that only small files will be uploaded to the server
web.config and httpRuntime tag
executionTimeout = Indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
maxRequestLength = ndicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB)
If you make it less that 4096 KB then you will have to check PostedFile.ContentLength to be smaller/equal with your web config maxRequestLength behind on the code. So you give user a message that the file are trying to upload is larger that you accept. If you dont catch this your page will crash!
 
2)control file extension
You can only do this by regural expression validator. Sent me the file extensions you would like and I will create the validator for you.
 
0
 
Kumaraswamy RCommented:

In the web.config

<configuration>
   <system.web>
      <httpRuntime>

<httpRuntime useFullyQualifiedRedirectUrl="true|false"
             maxRequestLength="size in kbytes"
             executionTimeout="seconds"
             minFreeThreads="number of threads"
             minFreeLocalRequestFreeThreads="number of threads"
             appRequestQueueLimit="number of requests"
             versionHeader="version string"/>


http://msdn.microsoft.com/en-us/library/e1f13641(VS.71).aspx

http://forums.asp.net/t/1286443.aspx
0
 
carlnorrbomCommented:
Hi,

You don't necessarily need to use regular expression validator, you can also use enum's like this:
Partial Class nuritat_20101123
    Inherits System.Web.UI.Page

    Enum ApprovedFileType
        tiff
        png
        jpg
        gif
        bmp
    End Enum

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        If FileUpload1.HasFile And FileUpload1.PostedFile.ContentLength < 5120000 Then
            Dim extension As ApprovedFileType
            Dim strFileName As String = FileUpload1.FileName.ToString()
            Dim strExtension As String = strFileName.Substring((strFileName.LastIndexOf(".") + 1), (strFileName.Length - (strFileName.LastIndexOf(".") + 1)))
            Dim isApproved As Boolean = False
            Try
                For Each extension In [Enum].GetValues(GetType(ApprovedFileType))
                    If String.Compare(strExtension, extension.ToString()) = 0 Then
                        isApproved = True
                        Exit For
                    End If
                Next
                If isApproved Then
                    FileUpload1.SaveAs(Server.MapPath("~/Uploads") & "/" & strFileName)
                End If
            Catch ex As Exception
                Throw New Exception("An error occured while trying to upload your file: ", ex)
            End Try
        Else
            Throw New Exception("Posted File Error")
        End If
    End Sub

End Class

Open in new window


/Carl.
0
 
nuritatAuthor Commented:
How do I close this question? I already awarded all the points and accepted multiple solutions..
0
 
Amandeep Singh BhullarCommented:
This question has been classified as abandoned and is being closed as part of the Cleanup Program. See my comment at the end of the question for more details.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.