2

请在下面找到我的代码。我试图限制用户上传小于 4 MB 的文件,但是当我选择 830 KB 的文件时,我得到的内容长度为 80 MB。
此代码flSignature.PostedFile.ContentLength不起作用。请帮忙。

TIA

string uploadMsg = "";
string appPath = Server.MapPath("~");
string parentpath = appPath + "\\app\\Pictures\\";
//To Upload Multiple Files on Single Click 
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
    HttpPostedFile hpf = hfc[i];

    if (hpf.ContentLength > 0)
    {
        //if (hpf.ContentLength > 4096)
        //{
        //   uploadMsg = "Collective file size is more than 4 MB.";
        //}
        //else
        //{
        if (hfc.AllKeys[i].Contains("flSignature"))
        {
            if (flSignature.PostedFile.ContentLength > 4096)
            { 
                uploadMsg = "Collective file size is more than 4 MB.";
                break;
            }
            else
            {
                if (Path.GetFileName(hpf.FileName).ToLower().Contains("xls") || Path.GetFileName(hpf.FileName).ToLower().Contains("doc"))
                {
                    showalert("Only Image can be uploaded.");
                }
                else
                {
                    hpf.SaveAs(parentpath + lblUniqueNo.Text + "_signature_" + Path.GetFileName(hpf.FileName));
                }
            }
        }
        else if (hfc.AllKeys[i].Contains("flPhoto"))
        {
            if (flPhoto.PostedFile.ContentLength > 4096)
            {
                uploadMsg = "Collective file size is more than 4 MB.";
                break;
            }
            else
            {
                if (Path.GetFileName(hpf.FileName).ToLower().Contains("xls") || Path.GetFileName(hpf.FileName).ToLower().Contains("doc"))
                {
                    showalert("Only Image can be uploaded.");
                }
                else
                {
                    hpf.SaveAs(parentpath + lblUniqueNo.Text + "_passport_" + Path.GetFileName(hpf.FileName));

                }
            }
        }
        else if (hfc.AllKeys[i].Contains("flIdentDoc"))
        {
            if (flIdentDoc.PostedFile.ContentLength > 4096)
            {
                uploadMsg = "Collective file size is more than 4 MB.";
                break;
            }
            else
            {
                hpf.SaveAs(parentpath + lblUniqueNo.Text + "_doc_" + Path.GetFileName(hpf.FileName));
            }
        }


        //}
    }
}
4

2 回答 2

5

ContentLength属性携带的值以字节而不是千字节表示。

因此,当您发出 时flSignature.PostedFile.ContentLength > 4096,您实际上是在检查上传文件的大小是否大于四千字节,而不是四兆字节。

尝试类似:

if (flSignature.PostedFile.ContentLength > 4096 * 1024)  // 4194304 bytes
{ 
    uploadMsg = "Collective file size is more than 4 MB.";
    break;
}
于 2012-11-01T11:43:19.740 回答
2

PostedFile.ContentLength必须工作,当您浏览的文件大小超过文件中需要的maxrequest最大长度时web.config

于 2012-11-01T11:26:03.083 回答