如果不使用flash或silverlight文件上传控件,就无法"干净利落".如果不使用这些方法,最好的办法就是maxRequestLength在web.config文件中设置.
例:
<system.web>
<httpRuntime maxRequestLength="1024"/>
Run Code Online (Sandbox Code Playgroud)
上面的示例将文件大小限制为1MB.如果用户尝试发送任何更大的内容,他们将收到一条错误消息,指出已超出最大请求长度.这不是一个漂亮的消息,但如果你想,你可以覆盖IIS中的错误页面,使其可能与您的网站匹配.
根据评论编辑:
所以你可能使用几种方法来从URL获取文件的请求,所以我将发布2个可能的解决方案.首先是使用.NET WebClient:
// This will get the file
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(DownloadCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
webClient.DownloadFileAsync(new Uri("http://www.somewhere.com/test.txt"), @"c:\test.txt");
private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
WebClient webClient = (WebClient)(sender);
// Cancel download if we are going to download more than we allow
if (e.TotalBytesToReceive > iMaxNumberOfBytesToAllow)
{
webClient.CancelAsync();
}
}
private void DownloadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是在执行下载之前执行基本Web请求以检查文件大小:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://www.somewhere.com/test.txt"));
webRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
if (fileSize < iMaxNumberOfBytesToAllow)
{
// Download the file
}
Run Code Online (Sandbox Code Playgroud)
希望其中一个解决方案有助于或至少让您走上正确的道路.
| 归档时间: |
|
| 查看次数: |
10901 次 |
| 最近记录: |