Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload file and validate file extension and file size MVC 5

Tags:

asp.net-mvc

I use the below code so to upload and check file extension and file size

Update 2 Controller

 public ActionResult Create([Bind(Include = "anak_ID,Pubdate,kind,title,file,details,link")] HttpPostedFileBase file, announcement announcement)
    {
        if (ModelState.IsValid)
        {
            db.announcement.Add(announcement);
            db.SaveChanges();
            TempData["notice"] = "Data saved";

            var allowedExtensions = new[] { ".pdf", ".zip", ".rar" };

            if (file!= null && file.ContentLength > 0)
            {
                var checkextension = Path.GetExtension(file.FileName).ToLower();


                if (itm.Contains(checkextension))
                    {
                        var extension = Path.GetExtension(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/Content/AnnFiles/" + "announcement_" + announcement.anak_ID + extension));

                        //save File
                        file.SaveAs(path);

                        //prepere announcement
                        announcement.file= @"announcement_" + announcement.anak_ID + extension;


                        //Code for Save data to announcement.

                        db.SaveChanges();
                        TempData["notice"] = "OK! the file is uploaded";
                    }
                    else
                    {

                        TempData["notice"] = "Select pdf or zip or rar less than 20Μ";

                    }

            }

            return RedirectToAction("Create", announcement);


        }

        return View(announcement);
    }

Create view the file field.

 <div class="form-group">
        @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-8">
            @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "input-file", type = "file", name = "file"} })

        </div>
    </div>

Create view (the part that I display message).

  @if (TempData["notice"] != null)
    {
        <div class="alert alert-danger fade in">
            <a href="#" class="close" data-dismiss="alert">&times;</a>
            @TempData["notice"]
        </div>
    }

It saves the record in db but in file field saves "System.Web.HttpPostedFileWrapper"

The problem started when I changed the if statement from

 if (file != null && file .ContentLength > 0)

to

if (file != null && file .ContentLength > 0 && allowedExtensions.Contains(Path.GetExtension(file .FileName).ToLower()) && file .ContentLength <= (20 * 1024))

so to check the file extension and file size.

Another problem is that it always displays the message "Select pdf or zip or rar less than 20Μ" and saves the record. I quess because of the System.Web.HttpPostedFileWrapper value. What I want to achieve is not to save the record when I select extension that is not allowed and the file name in the table. Thank you in advance

like image 745
touinta Avatar asked Apr 14 '16 09:04

touinta


People also ask

How can I get file extension in MVC?

string extension = Path. GetExtension(upload. FileName);

How check file extension is valid or not in C#?

bool CheckFileType(string fileName) { string ext = Path. GetExtension(fileName); switch (ext. ToLower()) { case ". gif": return true; case ".

How do I validate a file type upload?

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.


1 Answers

Look at these code.

added .png for testing, you can remove it.

var allowedExtensions = new[] { ".pdf", ".zip", ".rar" };
var checkextension = Path.GetExtension(file.FileName).ToLower();

if (!allowedExtensions.Contains(checkextension))
{
    TempData["notice"] = "Select pdf or zip or rar less than 20Μ";
}

foreach (var itm in allowedExtensions)
{
    if (itm.Contains(checkextension))
    {
        db.announcement.Add(announcement);
        dbo.SaveChanges();
    }
}

if (file != null && file.ContentLength > 0)
{
    foreach (var itm in allowedExtensions)
    {
        if (itm.Contains(checkextension))
        {
            var extension = Path.GetExtension(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/AnnFiles/" + "announcement_" + announcement.anak_ID + extension));

            //save File
            file.SaveAs(path);

            //prepere announcement
            announcement.file = @"announcement_" + announcement.anak_ID + extension;


            //Code for Save data to announcement.

            db.SaveChanges();
            TempData["notice"] = "OK! the file is uploaded";
        }
    }
}   
like image 196
Bharat Avatar answered Sep 30 '22 16:09

Bharat