加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 如何在MVC3中限制FileUpload中的文件类型?

发布时间:2020-12-16 04:03:46 所属栏目:asp.Net 来源:网络整理
导读:我有一个文件上传功能,用户可以上传文件.我想限制用户上传某些文件类型.允许的类型是:.doc,.xlsx,.txt,.jpeg. 我怎么能这样做? 这是我的实际文件上传代码: public ActionResult UploadFile(string AttachmentName,BugModel model) { BugModel bug = null;
我有一个文件上传功能,用户可以上传文件.我想限制用户上传某些文件类型.允许的类型是:.doc,.xlsx,.txt,.jpeg.

我怎么能这样做?

这是我的实际文件上传代码:

public ActionResult UploadFile(string AttachmentName,BugModel model)
       {            
        BugModel bug = null;
        if (Session["CaptureData"] == null)
        {
            bug = model;
        }
        else
        {
            bug = (BugModel)Session["CaptureData"];
        }
        foreach (string inputTagName in Request.Files)
        {
            HttpPostedFileBase file1 = Request.Files[inputTagName];
            if (file1.ContentLength > 0)
            {
                string path = "/Content/UploadedFiles/" + Path.GetFileName(file1.FileName);
                string savedFileName = Path.Combine(Server.MapPath("~" + path));
                file1.SaveAs(savedFileName);
                BugAttachment attachment = new BugAttachment();
                attachment.FileName = "~" + path.ToString();
                attachment.AttachmentName = AttachmentName;
                attachment.AttachmentUrl = attachment.FileName;
                bug.ListFile.Add(attachment);
                model = bug;
                Session["CaptureData"] = model;
            }
        }
        ModelState.Clear();
        return View("LoadBug",bug);
    }

解决方法

要验证的第一件事是file1.FileName中包含的文件扩展名是否与允许的扩展名之一匹配.然后,如果您确实希望确保用户未将某些其他文件类型重命名为允许的扩展名,则需要查看该文件的内容以识别它是否是允许的类型之一.

以下是如何检查文件扩展名是否属于预定义扩展名列表的示例:

var allowedExtensions = new[] { ".doc",".xlsx",".txt",".jpeg" };
var extension = Path.GetExtension(file1.FileName);
if (!allowedExtensions.Contains(extension))
{
    // Not allowed
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读