[英]Limit on a file size server side in C#
我目前正在 MVC4 中上傳文件,但在我的控制器中,我試圖將文件大小限制為最大 4MB,但收到以下警告
comparison to integral constant is useless
使用Haacks示例
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
if (file.ContentLength < 4000000000 )
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
當我運行代碼時出現錯誤
Maximum request length exceeded.
由於file.ContentLength
是一個我無法控制的int
我不知道解決這個問題的方法是什么。 任何人都可以幫助我如何限制文件大小服務器端。
編輯對於那些可能想指出4000000000
是4gb
您是對的。 但是,即使我用4000000
替換它,我的操作也會成功完成,但不會保存文件,因為我的If()
不滿意,即file.ContentLength < 4000000
返回 false。
編輯這不是一個重復的問題我想將我的文件大小限制在某個限制而不是忽略 IIS 中的文件大小限制。
在您的 web.config 中設置此值
<httpRuntime maxRequestLength="4096"/>
對於那些使用IFormFile
您可以使用以下內容。
[HttpPost]
public ActionResult Upload(IFormFile file)
{
int fourMB = 4 * 1024 * 1024;
var fileSize = file.Length;//Get the file length in bytes
if (fileSize / 1048576.0 > fourMB) //1048576 (i.e. 1024 * 1024):
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.