2

I'm trying to restrict how large a file a user can upload on a particular page. I've done this using web.config like this:

<location path="SubSection/TestPage">
    <system.web>
        <httpRuntime maxRequestLength="2048" />
    </system.web>
</location>

However, when this errors, it takes the user to one of those ASP.NET yellow-error pages. Now I know it is possible to create custom error pages, and I've looked into this, but they still involve redirecting the browser.

This is simply for trying inform the user that they are trying to upload a file that is too large, without navigating them away from the page they are currently on. Is it possible to prevent this TestPage from redirecting to the yellow-error page, and instead display a JavaScript popup of some kind?

I have tried to handle the error in the Application_Error() method in the global.asax file, but unfortunately it always seems to redirect after this method finishes, regardless of what I do in it. My attempts to display a JavaScript popup through this page were also not successful, although my understanding is that this is actually possible in the global.asax file, so I would assume I'm simply doing something wrong there.

This is my code for handling Application_Error(), based on the accepted answer from here, with the JavaScript part based on this.

void Application_Error(object sender, EventArgs e) 
{
    int TimedOutExceptionCode = -2147467259;
    Exception mainEx;
    Exception lastEx = Server.GetLastError();
    HttpUnhandledException unhandledEx = lastEx as HttpUnhandledException;

    if (unhandledEx != null && unhandledEx.ErrorCode == TimedOutExceptionCode)
    {
        mainEx = unhandledEx.InnerException;
    }
    else
        mainEx = lastEx;

    HttpException httpEx = mainEx as HttpException;

    if (httpEx != null && httpEx.ErrorCode == TimedOutExceptionCode)
    {
        if(httpEx.StackTrace.Contains("GetEntireRawContent"))
        {
            System.Web.UI.Page myPage = (System.Web.UI.Page)HttpContext.Current.Handler;
            myPage.RegisterStartupScript("alert","<script language=javascript>alert('The file you attempted to upload was too large.  Please try another.');</script" + ">");
            Server.ClearError();
        }
    }
}

Finally, I have also tried the following code in the user control itself (which is in VB.NET), based on the accepted answer from this:

    Private Sub Page_Error(ByVal sender As Object, ByVal e As EventArgs)
        Dim err As Exception = Server.GetLastError()
        Dim cs As ClientScriptManager = Page.ClientScript
        If (cs.IsStartupScriptRegistered(Me.GetType(), "testJS") = False)
            Dim cstext1 As String = "alert('" & err.Message & "');"
            cs.RegisterStartupScript(Me.GetType(), "testJS", cstext1, True)
        End If
    End Sub

Unfortunately, this code did not seem to get called at all.

To reiterate, this is just for handling, say, a simple user mistake in uploading a file that is slightly too large. I don't want to redirect and lose what else the user may have done on the original page, I just want to display a simple JavaScript alert box. Can this be done?

Community
  • 1
  • 1
Interminable
  • 1,338
  • 3
  • 21
  • 52
  • you just need to check the file size.. if it exceeds than that size then you should have to show alert message that is much pretty simple.. – Ram Singh Nov 12 '13 at 04:02

2 Answers2

0

you can get the file size in java script like follow.

var fileSize = document.getElementById("myfileUploader").files[0].size; //gives size in bytes.

if(fileSize > 2097152)   //2038Kb = 2038*1024 bytes
{
 alert("File size exceded");
return false;
}
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
  • 1
    This will not work on IE. Also, you're checking against 2048 BYTES (as you state in the comment), but the config shown by the OP is based on **Kb**, so it should be `fileSize > 2097152` instead – freefaller Sep 09 '13 at 12:01
  • On the positive side, I didn't know about this ability in non-IE browsers, so thanks for that :-) – freefaller Sep 09 '13 at 12:09
  • This JavaScript solution requires that the file selected by the user finishes uploading first, right? If so, that will mean that it will hit the `maxRequestLength` limit before it hits the JavaScript, won't it? – Interminable Sep 09 '13 at 13:08
0

You can send the request using AJAX and handle an error response as an indication that the files are too large. For example, using jQuery:

$.ajax("/my/upload/action",
    {
        type: "POST",
        data-type: "xml",
        data: serializeFilesAsXML();
        success: function() {
            alert("Your files were uploaded!");
        }
        error: function(jqXHR, textStatus, errorThrown) {
            if(errorThrown == "Files Too Large") {
                alert("Your files were too large.");
            } else {
                alert("There was an error uploading your files. Please try again.");
            }
        }
    }
);

You may need to rewrite your action for uploading files so that it responds to AJAX requests and can send appropriate failure messages.

Kevin
  • 14,655
  • 24
  • 74
  • 124