0

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

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

if it solves your problem then accepted answer will be appriciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.