touinta
touinta

Reputation: 1031

Upload file and validate file extension and file size MVC 5

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

Upvotes: 8

Views: 27422

Answers (1)

Bharat
Bharat

Reputation: 6095

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

Upvotes: 8

Related Questions