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

Asp.net mvc 3 如何在MVC3中限制FileUpload中的文件类型?,asp.net-mvc-3,file-upload,Asp.net Mvc 3,File Upload,我有一个文件上传功能,用户可以上传文件。我想限制用户上传某些文件类型。允许的类型有:.doc、.xlsx、.txt、.jpeg 我怎么能做到 这是我的实际文件上载代码: public ActionResult UploadFile(string AttachmentName, BugModel model) { BugModel bug = null; if (Session["CaptureData"] == n

我有一个文件上传功能,用户可以上传文件。我想限制用户上传某些文件类型。允许的类型有:.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
}

您可以使用
HttpPostedFileBase
ContentType
属性对文件类型(mime类型)进行基本检查:

以下是一种方法:

private static bool IsValidContentType(string contentType)
{
    string ct = contentType.ToLower();

    return ((ct == "application/msword") || (ct == "application/pdf") || (ct == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
}
等等

但是,为了进行更深入的检查,您必须检查文件内容。更改文件扩展名很容易

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class AllowedFileExtensionAttribute : ValidationAttribute
{
    public string[] AllowedFileExtensions { get; private set; }
    public AllowedFileExtensionAttribute(params string[] allowedFileExtensions)
    {
        AllowedFileExtensions = allowedFileExtensions;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var file = value as HttpPostedFileBase;
        if (file != null)
        {
            if (!AllowedFileExtensions.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase)))
            {
                return new ValidationResult(string.Format("{1} için izin verilen dosya uzantıları : {0} : {2}", string.Join(", ", AllowedFileExtensions), validationContext.DisplayName, this.ErrorMessage));
            }
        }
        return null;
    }
}
模型中的用法

    [AllowedFileExtension(".jpg", ".png", ".gif", ".jpeg")]
    public HttpPostedFileBase KategoriResmi { get; set; }

@Darrin Dimitrov…感谢您的帮助,在保存数据库之前,我会在表中显示上传的文件…如果用户想要删除其中一个上传的文件,我该如何做…这是实际的答案这是实际的简洁答案。非常感谢。