Solved

How can I control file size in Upload control?

Posted on 2010-11-23
9
355 Views
Last Modified: 2012-05-10
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
0
Comment
Question by:nuritat
9 Comments
 
LVL 4

Assisted Solution

by:Andre412
Andre412 earned 25 total points
ID: 34195781
To only take action when say less than 5MB

If UploadControl.PostedFile.ContentLength < 500000I Then
0
 
LVL 18

Expert Comment

by:carlnorrbom
ID: 34195889
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
 
LVL 3

Assisted Solution

by:Sokrates
Sokrates earned 25 total points
ID: 34195932
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
 
LVL 29

Assisted Solution

by:Kumaraswamy R
Kumaraswamy R earned 25 total points
ID: 34196009

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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 18

Assisted Solution

by:carlnorrbom
carlnorrbom earned 25 total points
ID: 34196556
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
 
LVL 5

Accepted Solution

by:
JayFromPep earned 25 total points
ID: 34196616
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
 

Author Comment

by:nuritat
ID: 34212106
How do I close this question? I already awarded all the points and accepted multiple solutions..
0
 
LVL 19

Expert Comment

by:Amandeep Singh Bhullar
ID: 34882113
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

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Introduction During my participation as a VBScript contributor at Experts Exchange, one of the most common questions I come across is this: "I have a script that runs against only one computer. How can I make it run against a list of computers in …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video discusses moving either the default database or any database to a new volume.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now