开发者

better way of showing File Upload Errors?

Model:

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 Provid开发者_C百科e 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;  
        }  
    }
}    

And my controller file

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

Now the Problem

From the form i am getting Name,Email, Message and uploaded file. I can get validation errors automatically for Name,Email,Message using public string this [string propName]. How can i show validation errors if Attachment.FileSize > 10000? If i write its code in

public string this [string propName]

i alwasy getting Attachment null. How can i fill Attachment Object of ContactEmail so that i can manage all errors on same place?


you can upload by calling UploadFiles(form,"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;
            }

        }

    }

it would be easy to add hpf.ContentLength into a variable and run an if on its size and then have

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

seems as modelstate is still valid this will then show on your error summary just modify the example code to add your own restrictions and checks.

typing hpf. should then give you all the extensions available for extension etc too

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜