2012-11-01 147 views
2

請在下面找到我的代碼。我試圖限制用戶上傳小於4MB的文件,但是當我選擇一個830KB的文件時,我得到的內容長度爲80MB。
此代碼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

ContentLength屬性攜帶的值以字節爲單位表示,不千字節。

因此,當您發出flSignature.PostedFile.ContentLength > 4096時,實際上是在檢查上傳文件的大小是否大於4千字節而不是4兆字節。

試着這麼做:

if (flSignature.PostedFile.ContentLength > 4096 * 1024) // 4194304 bytes 
{ 
    uploadMsg = "Collective file size is more than 4 MB."; 
    break; 
} 
2

PostedFile.ContentLength有工作,當你正在瀏覽的多個大小的文件比你需要maxrequest長度最大的web.config文件

+0

它不工作flSignature.PostedFile.ContentLength代碼返回80 MB我很困惑,文件大小僅800 KB – user1448912