How can I handle maxRequestLength exceptions elegantly?

后端 未结 3 1283
醉酒成梦
醉酒成梦 2021-01-03 11:45

In my ASP.NET MVC (v2 if it matters) app, I have a page that allows the user to upload a file. I\'ve configured the maxRequestLength for my app to allow files up to 25MB.

相关标签:
3条回答
  • 2021-01-03 12:26

    http://nishantrana.wordpress.com/2009/01/19/fileupload-page-cannot-be-displayed-and-maximum-request-length-exceeded-error/

    Try the last solution here, I tried it and works fine.

    0 讨论(0)
  • 2021-01-03 12:38

    To my knowledge, there is no way to gracefully handle exceeding IIS's "maxRequestLength" setting. It can't even display a custom error page (since there is no corresponding HTTP code to respond to). The only way around this is to set maxRequestLength to some absurdly high number of kbytes, for example 51200 (50MB), and then check the ContentLength after the file has been uploaded (assuming the request didn't time out before 90 seconds). At that point, I can validate if the file <=5MB and display a friendly error.

    0 讨论(0)
  • 2021-01-03 12:39

    I got around this problem by making the page invalid (so it won't post back) if the chosen file is over the max request length. It requires having a custom validation control for the client side, validating the fileupload control. Here is the server validation sub, for limiting file size to 4Mb:

    Sub custvalFileSize_ServerValidate(ByVal s As Object, ByVal e As ServerValidateEventArgs)
            'FileUpload1 size has to be under 4Mb
            If (FileUpload1.PostedFile.ContentLength > 4194304) Then
                e.IsValid = False
            Else
                e.IsValid = True
            End If
    End Sub
    

    Here is the client side validation function:

    function custvalFileSize_ClientValidate(src,args){
        if (document.all("FileUpload1").files[0].size > 4194304){
            args.IsValid = false;
        } else {
            args.IsValid = true;
        }
    }
    

    The upload control and validation control:

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:CustomValidator ID="CustomValidator1" runat="server" BackColor="#FFFFFF" BorderColor="#FF0000"                                BorderStyle="solid" BorderWidth="0" ClientValidationFunction="custvalFileSize_ClientValidate"                    ControlToValidate="FileUpload1" Display="Dynamic" EnableClientScript="true" ErrorMessage="<b>Please upload document files of 4Mb or less.</b>"
    Font-Bold="false" Font-Names="Verdana, Arial, Helvetica" Font-Size="9px" ForeColor="#FF0000"                              OnServerValidate="custvalFileSize_ServerValidate" Text="<br/><span style='font-weight:bold;font-size:12px;'>This file is too large.<br />We can only accept documents of 4Mb or less.</span>"></asp:CustomValidator>
    
    0 讨论(0)
提交回复
热议问题