上传文件并验证文件扩展名和文件大小MVC 5

时间:2016-04-14 09:45:04

标签: asp.net-mvc

我使用以下代码,以便上传和检查文件扩展名和文件大小

更新2 控制器

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

创建视图文件字段。

 <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>

创建视图(我显示消息的部分)。

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

它将记录保存在db中但在文件字段中保存“System.Web.HttpPostedFileWrapper”

当我从

更改if语句时,问题就开始了
 if (file != null && file .ContentLength > 0)

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

所以检查文件扩展名和文件大小。

另一个问题是它始终显示消息 “选择pdf或zip或rar小于20M”并保存记录。我因为System.Web.HttpPostedFileWrapper值而退出。我想要实现的是当我选择不允许的扩展名和表中的文件名时保存记录。 提前谢谢

1 个答案:

答案 0 :(得分:6)

看看这些代码。

添加.png进行测试,您可以将其删除。

if (ModelState.IsValid)
{ 
   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";
                        }
                    }

                }
            }
}