Created
February 19, 2013 07:38
-
-
Save forcewake/4983817 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Upload | |
{ | |
public string Name { get; set; } | |
[FileSize(655360)] | |
[FileTypes("jpg,jpeg,png")] | |
public HttpPostedFileBase File { get; set; } | |
} | |
[HttpPost] | |
[Authorize] | |
public ActionResult Upload(Upload upload) | |
{ | |
string path = @"D:\Temp\"; | |
if (ModelState.IsValid) | |
{ | |
if (upload != null && upload.File != null) | |
upload.File.SaveAs(path + WebMatrix.WebData.WebSecurity.CurrentUserId+"_"+DateTime.Now.ToShortDateString()); | |
return RedirectToAction("Index"); | |
} | |
return View(); | |
} | |
[Authorize] | |
[HttpGet] | |
public ActionResult Upload() | |
{ | |
ViewBag.Message = "Opa!"; | |
return View(); | |
} | |
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) | |
{ | |
<label for="file">Photo:</label> | |
<input type="file" name="File"/> | |
<input type="submit" /> | |
} | |
public class FileSizeAttribute : ValidationAttribute | |
{ | |
private readonly int _maxSize; | |
public FileSizeAttribute(int maxSize) | |
{ | |
_maxSize = maxSize; | |
} | |
public override bool IsValid(object value) | |
{ | |
if (value == null) return true; | |
HttpPostedFileWrapper httpPostedFileWrapper = value as HttpPostedFileWrapper; | |
return httpPostedFileWrapper != null && _maxSize > httpPostedFileWrapper.ContentLength; | |
} | |
public override string FormatErrorMessage(string name) | |
{ | |
return string.Format("The file size should not exceed {0}", _maxSize); | |
} | |
} | |
public class FileTypesAttribute : ValidationAttribute | |
{ | |
private readonly List<string> _types; | |
public FileTypesAttribute(string types) | |
{ | |
_types = types.Split(',').ToList(); | |
} | |
public override bool IsValid(object value) | |
{ | |
if (value == null) return true; | |
HttpPostedFileWrapper httpPostedFile = value as HttpPostedFileWrapper; | |
if (httpPostedFile != null) | |
{ | |
var extension = System.IO.Path.GetExtension(httpPostedFile.FileName); | |
if (extension != null) | |
{ | |
var fileExt = extension.Substring(1); | |
return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase); | |
} | |
} | |
return true; | |
} | |
public override string FormatErrorMessage(string name) | |
{ | |
return string.Format("Invalid file type. Only the following types {0} are supported.", String.Join(", ", _types)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment