解决C#fileupload异常超出最大请求长度

时间:2015-04-15 22:53:57

标签: c# asp.net exception gridview file-upload

我制作了一个webusercontrol上传图片和文档,因此当用户上传图片文件时,该文件会转到Images文件夹,当用户上传doc文件时,它会转到Documents文件夹。 当我尝试上传文件大小的文件或文件大小的文件时,似乎我遇到了问题,总是出现错误页面和System.Web.HttpException:超出了写在该页面上的最大请求长度。如何使用try-catch-block

解决此问题
protected void btnsubmit_Click(object sender, EventArgs e)
{

    string [] img = {"bmp","gif","png","jpg","jpeg"};
    string ext = System.IO.Path.GetExtension(FileUpload.PostedFile.FileName);  
    bool isValidFile = false;
    for (int i = 0; i < img.Length; i++)
    {
    if (ext == "." + img[i] )
    {
        isValidFile = true;
        break;
    }
    }
    if (!FileUpload.HasFile)
    {
        lblMessage.Text = "You must select a file before pressing the submit button!";
    }
    else if (StoreFolders.ToString() == "Images/")
    {
        if (!isValidFile)
        {
            lblMessage.Text = "You can only upload Image files!";
        }
        else
        {
                FileUpload.PostedFile.SaveAs(Server.MapPath(StoreFolders) + FileUpload.FileName);
                lblMessage.Text = "Your file is saved succesfully!";
                Dtable.Rows.Add(FileUpload.FileName, "(" + GetSize(FileUpload.FileBytes.Length) + " )", DateTime.Now);
        }

    }
    else if(StoreFolders.ToString() == "Documents/")
    {
        if (isValidFile)
        {
            lblMessage.Text = "You can only upload Document files!";
        }
        else
        {
            FileUpload.PostedFile.SaveAs(Server.MapPath(StoreFolders) + FileUpload.FileName);
            lblMessage.Text = "Your file is saved succesfully!";
            Dtable.Rows.Add(FileUpload.FileName, "(" + GetSize(FileUpload.FileBytes.Length) + " )", DateTime.Now);
        }

    }
    GridView1.DataSource = Dtable;
    GridView1.DataBind();

}

1 个答案:

答案 0 :(得分:1)

您要做的第一件事是配置您的应用以允许预期的文件大小,如下所述:

Maximum request length exceeded

那么你可以尝试类似答案: Catching "Maximum request length exceeded"