ASP.net MVC限制上传文件
本文关键字:文件 net MVC ASP | 更新日期: 2023-09-27 18:13:59
我有一个上传方法在我的一个控制器在我的ASP.net项目工作完美,但我该如何添加限制文件类型;Jpeg, jpg, PNG和bmp.
我在网上到处看了看,有很多解决方案,但没有一个适合我。
我的代码
public ActionResult Create([Bind(Include = "Id,Title,Description,FileName,FileType,FileSize,Author,DateUploaded")] FileSharing fileSharing)
{
if (Request.Files.Count > 0)
{
if (ModelState.IsValid)
{
HttpPostedFileBase file = Request.Files.Get(0);
string fileName = Path.GetFileName(file.FileName);
string filePath = Path.Combine(Server.MapPath("~/Assets/"), fileName);
file.SaveAs(filePath);
FileInfo fileInfo = new FileInfo(filePath);
fileSharing.FileType = fileInfo.Extension.Remove(0, 1).ToUpper();
fileSharing.DateUploaded = DateTime.Now;
fileSharing.FileName = fileName;
fileSharing.FileSize = fileInfo.Length.ToString();
fileSharing.Author = User.Identity.Name;
db.FileSharing.Add(fileSharing);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(fileSharing);
}
您可以通过
检查文件扩展名HttpPostedFileBase file = Request.Files.Get(0);
var allowedExtensions = new string[]{".jpeg", ".png"};
string extension = Path.GetExtension(file.FileName);
if(allowedExtensions.Contains(extension))
{
//file allowed
}
else
{
//invalid extension
}
获取如下扩展名
var FileExtension = Path.GetExtension(fileName).ToLower();
并将其与file.SaveAs(filePath);
if(FileExtension == ".jpg" || FileExtension == ".bmp" |....)