更好的显示文件上传错误的方法?

时间:2010-04-25 09:32:01

标签: c# asp.net-mvc

型号:

public class EmailAttachment  
{  
    public string FileName { get; set; }  
    public string FileType { get; set; }  
    public int FileSize { get; set; }  
    public Stream FileData { get; set; }  
}  

public class ContactEmail: IDataErrorInfo  
{  
    public string Name { get; set; }  
    public string Email { get; set; }  
    public string Message { get; set; }  
    public EmailAttachment Attachment { get; set; }  

    public string Error { get { return null; } }  

    public string this[string propName]  
    {
        get  
        {  
            if (propName == "Name" && String.IsNullOrEmpty(Name))  
                return "Please Enter your Name";  
            if (propName == "Email"){  
                if(String.IsNullOrEmpty(Email))  
                    return "Please Provide an Email Address";  
                else if(!Regex.IsMatch(Email, ".+\\@.+\\..+"))  
                    return "Please Enter a valid email Address";  
            }  

            if (propName == "Message" && String.IsNullOrEmpty(Message))  
                return "Please Enter your Message";  
            return null;  
        }  
    }
}    

我的控制器文件

[AcceptVerbs(HttpVerbs.Post)]  
public ActionResult Con(ContactEmail ce, HttpPostedFileBase file)  
{  
    return View();  
}  

现在问题是 从表格我得到名称,电子邮件,消息和上传的文件。我可以使用公共字符串[string propName]自动为名称,电子邮件,消息获取验证错误。如果Attachment.FileSize>如何显示验证错误? 10000?如果我在其中编写代码 public string this [string propName]
我alwasy得到附件null。如何填写ContactEmail的附件对象,以便我可以管理同一地点的所有错误?

1 个答案:

答案 0 :(得分:0)

您可以通过调用UploadFiles(表单,“folderForFiles);

上传
public void UploadFiles(FormCollection form, string folder)
    {
        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file];

            if (hpf.ContentLength == 0)
            {
                form[file] = null;
            }
            else
            {
                var filename = hpf.FileName.Replace(" ", "_").Replace(".", DateTime.Now.Date.Ticks + ".");

                UploadFileName = filename;
                hpf.SaveAs(Server.MapPath("~/Content/" + folder + "/" + filename));

                form[file] = UploadFileName;
            }

        }

    }

将hpf.ContentLength添加到变量并在其大小上运行if会很容易

ModelState.AddModelError("","File is too large to be uploaded");
return;

似乎模型状态仍然有效,然后会显示在您的错误摘要中 只需修改示例代码即可添加自己的限制和检查。

输入hpf。然后应该给你所有可用于扩展的扩展等