7

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

touinta
  • 971
  • 3
  • 10
  • 26
  • do you have get method of create? – Bharat Apr 14 '16 at 09:57
  • Yes I have is simple the `public ActionResult Create() { webdata db = new webdata(); ViewBag.kind = new SelectList(db.announcementCategories, "kind", "an_kindtext"); return View(); }` – touinta Apr 14 '16 at 10:38
  • just use || instead of && for testing, if it works then ping me.. – Bharat Apr 14 '16 at 10:46
  • Now when I dont select a file (its not a required field) it returns: `Object reference not set to an instance of an object.` at the line ` if (file!= null || file.ContentLength > 0 || allowedExtensions.Contains(Path.GetExtension(file.FileName).ToLower()) || file.ContentLength <= (20 * 1024))` When I select a file whatever extension it saves it with correct name. But it doesn't check the extension. thank you – touinta Apr 14 '16 at 10:59
  • Try this : string fileName = System.IO.Path.GetFileName(File.FileName); string extantion = System.IO.Path.GetExtension(fileName); and then check this extantion variable in contains function – Varun Vasishtha Apr 14 '16 at 11:04
  • thank you but same thing it saves all the files no matter the extension is. – touinta Apr 14 '16 at 11:12
  • put your code in fiiddle – Bharat Apr 14 '16 at 11:40

1 Answers1

8

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";
        }
    }
}   
Bharat
  • 5,869
  • 4
  • 38
  • 58
  • thank you for your reply, now 1) when I dont choose a file it saves correct the record but shows the message ""Select pdf or zip..." 2) When I choose other extension lets say .jpg it saves the record, and puts "System.Web.HttpPostedFileWrapper" at the file field and no message and 3) When I choose appropriate extension file it stores the record ok. – touinta Apr 14 '16 at 12:16
  • is it ok? or do you need anything else? if not then please upvote my answer, it will really helps me... – Bharat Apr 14 '16 at 12:17
  • 1
    well its not ok because when I choose other extensions again save the record. I need no to save the record and to display the error message like "Select pdf or zip or rar less than 20Μ". Also I dont need to display the error message when no file is selected. Its not a required field. thank you very much – touinta Apr 14 '16 at 12:21
  • hi again. Now when I dont choose file it doesn't save the record at all. I need to save the record and in that case. File field its not a required field. When I choose pdf or other appropriate extension it displays the message "Select pdf...." and it save the file in format "announcement_0". That why I had the db.SaveChanges twice because I need the ID (anak_id) for the file name. When I select other extension it doesnt save the record at all and displays the message this is correct. Thank you – touinta Apr 14 '16 at 13:14
  • hey touinta, i have give you full example, you just need to change if-else. my friend.. currently i am on meeting. – Bharat Apr 14 '16 at 13:28
  • yes I know but I am at almost to the same result. I dont want to disturb you from your meeting. I will give a try...thank you. – touinta Apr 14 '16 at 13:44
  • Hello, I manage to fix the most of the issues. The only thing that is wrong now is that I dont need to save the record when the file is not an appropriate extension. It displays the message, but since the model is valid it saves the record too. Any idea? – touinta Apr 15 '16 at 06:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109222/discussion-between-bharat-and-touinta). – Bharat Apr 15 '16 at 06:49