获取上传文件的大小c# MVC
本文关键字:MVC 文件 获取 | 更新日期: 2023-09-27 18:15:30
我正在尝试创建一些文件大小的验证。我的代码:
[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;
我收到错误:"文件无法找到"。你知道如何解决这个问题吗?
. Net MVC,我们必须使用HttpPostedFileBase
上传文件,如下所示:-
public ActionResult Index(FotoModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; // <---Your file Size or Length
.............
.............
}
}
您要查看的是ContentLength
public ActionResult Index(FotoModel model)
{
if (model != null && model.File != null)
{
var fileSize = model.File.ContentLength;
}
}