天天看點

上傳檔案檢測大小的幾種方式

最近做了個附件上傳的功能,對于附件大小的檢測難了我一把。之前都是簡單的用FileUpload1.PostedFile.ContentLength 判斷的,可是上司發現如果上傳幾百兆的檔案時,會等很久然後彈出來提示框,使用者體驗非常不好。于是乎,我左百度,右谷歌,再加上Q群求助,博問懸賞…

忙活了半天。雖然最終上司說“就這樣吧”而告終,不過研究的過程也學到了一些小知識,簡單記錄下。

這個是我經常用的一種方式,不過上傳大檔案就會發現他是上傳之後才檢測檔案大小的。使用者體驗不是太好

前台: <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="上傳" /> 背景: if (FileUpload1.PostedFile.ContentLength > 10485760) { MessageBox.Show("上傳檔案請不要超過10M"); return; } string filepath = FileUpload1.FileName;//本地路徑 。。。 FileUpload1.SaveAs(sSavePath);

這個測試發現其實也是上傳之後才進行判斷的,跟上一個的性能差不多。

<input type="file" runat="server" id="FileUpload1" /> <asp:Button ID="btnUpload" runat="server" Text="上傳" onClick="btnUpload_Click" /> HttpPostedFile f = Request.Files[0]; if (f.ContentLength > 10485760) string filepath1 = FileUpload1.Value;//本地路徑D:/.. f.SaveAs(sSavePath);

用戶端檢測檔案大小 ,這個倒是在用戶端檢測的,但是會彈出安全提示。

&lt;html&gt; &lt;head&gt; &lt;script&gt; function getFileSize(fileName) { if (document.all) { window.oldOnError = window.onerror; window.onerror = function (err) { if (err.indexOf('utomation') != -1) { alert('沒有通路檔案的權限'); return true; else return false; }; var fso = new ActiveXObject('Scripting.FileSystemObject'); var file = fso.GetFile(fileName); window.onerror = window.oldOnError; return parseInt(file.Size / 1024) + 'K'; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="formName"&gt; &lt;input type="file" name="fileName" onchange="alert(getFileSize(this.form.fileName.value))"&gt;&lt;br&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; <a href="http://images.cnblogs.com/cnblogs_com/janes/201202/201202091343162914.png"></a>

<a href="http://images.cnblogs.com/cnblogs_com/janes/201202/201202091343171028.png"></a>

雖然這次沒能把這個方案用上去,不過對自己來說也是一次不錯的學習過程。希望下回能夠用它來完善程式的客戶體驗。

    本文轉自 陳敬(Cathy) 部落格園部落格,原文連結:http://www.cnblogs.com/janes/archive/2011/11/16/2251471.html,如需轉載請自行聯系原作者

繼續閱讀