在我的asp .net项目中,我的主页面接收URL作为参数,我需要内部下载并处理它。我知道我可以使用WebClient的DownloadFile方法,但我想避免恶意用户提供一个巨大文件的url,这将导致我的服务器产生不必要的流量。为了避免这种情况,我正在寻找一种解决方案来设置DownloadFile将下载的最大文件大小。
谢谢您的帮助,
杰克
谢谢您的帮助,
杰克
如果不使用Flash或Silverlight文件上传控件,就没有办法“干净地”实现这一点。在不使用这些方法的情况下,您可以在web.config文件中设置maxRequestLength
。
示例:
<system.web>
<httpRuntime maxRequestLength="1024"/>
// 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
}
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
}
DownloadProgressChangedEventHandler
的解决方案不起作用。 - Toolkitvar webClient = new WebClient();
client.OpenRead(url);
Int64 bytesTotal = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);
然后您可以决定 bytesTotal
是否在限制范围内。