获取上传文件C#MVC的大小

时间:2014-07-30 11:04:07

标签: c# asp.net-mvc fileinfo

我正在尝试为文件大小创建一些验证。我的代码:

    [HttpPost]
    public ActionResult Index(FotoModel model)
    {
        TryUpdateModel(model);
        if (ModelState.IsValid)
        {
            if (model != null && model.File != null)
            {
                var fileName = Path.GetFileName(model.File.FileName);
                var fileExtension = Path.GetExtension(fileName);
                long fileSize = new FileInfo(fileName).Length;
                fileName = "file" + fileExtension;
                var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
                if (fileSize < 55000)
                {
                    model.File.SaveAs(path);
                    model.link = fileName.ToString();
                }
                else
                {
                    ViewData["Size"] = "Akceptowane pliki: jpg, jpeg, png o maksymalnym rozmiarze 50 KB";
                }

                return View(model);
            }
        }
        return View(model);
    }

在这一行:

long fileSize = new FileInfo(fileName).Length;

我收到错误:“无法找到文件”。你知道我怎么解决这个问题?

2 个答案:

答案 0 :(得分:7)

在Asp.Net MVC中,我们必须使用HttpPostedFileBase来上传文件,如下所示: -

public ActionResult Index(FotoModel model, HttpPostedFileBase file)
{
  if (file != null)
        {
            int byteCount = file.ContentLength;  // <---Your file Size or Length
            .............
            .............
        }
}

答案 1 :(得分:1)

您所看到的是ContentLength

    public ActionResult Index(FotoModel model)
    {
        if (model != null && model.File != null)
        {
            var fileSize = model.File.ContentLength;
        }
    }