Solved

How can I control file size in Upload control?

Posted on 2010-11-23
9
359 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is the result of a quest to better understand Task Scheduler 2.0 and all the newer objects available in vbscript in this version over  the limited options we had scripting in Task Scheduler 1.0.  As I started my journey of knowledge I f…
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

751 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