简体   繁体   中英

ASP.net MVC Restricting Upload files

I have a upload method within one of my controllers in my ASP.net project which works perfectly, but how would I add to restrict to file types; jpeg, jpg, png and bmp.

I've looked everywhere online and there was a lot of solutions but none of them worked for me.

Here is my code

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);
    }

You can check file exenstions by

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
}

Get extension as below

var FileExtension = Path.GetExtension(fileName).ToLower();

And compare it with your desired formats before file.SaveAs(filePath);

if(FileExtension == ".jpg" || FileExtension == ".bmp" |....)

Then only save.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM