上传文件并验证文件扩展名和文件大小MVC 5 [英] Upload file and validate file extension and file size MVC 5

查看:137
本文介绍了上传文件并验证文件扩展名和文件大小MVC 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

当我从以下位置更改if语句时,问题就开始了

The problem started when I changed the if statement from

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

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.

另一个问题是它总是显示消息 选择小于20Μ的pdf或zip或rar"并保存记录.我因System.Web.HttpPostedFileWrapper值而提问.我想实现的是不保存记录时,我选择的扩展,是不允许的,在表中的文件名. 预先谢谢你

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

推荐答案

查看这些代码.

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

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

这篇关于上传文件并验证文件扩展名和文件大小MVC 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆