asp.net mvc 3 razor file upload

后端 未结 3 1381
温柔的废话
温柔的废话 2020-12-30 17:14

Which is best way to upload single file with asp.net mvc3 razor and validate with jquery.

I only need to user upload jpg, png less then 5 mb.

Thanks

3条回答
  •  渐次进展
    2020-12-30 17:48

    Aside jQuery validation (very nice Acid's answer) You should also do server validation. Here's some simple example:

    VIEW:

    @if (TempData["imageUploadFailure"] != null)
    {
        @* Here some jQuery popup for example *@
    }
    
    @using (Html.BeginForm("ImageUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {                  
        Add Image
    
        
        
        
    }

    CONTROLLER:

    public ActionResult ImageUpload()
    {
        return View();
    }
    
    [HttpPost]
    public ActionResult ImageUpload(HttpPostedFileBase image)
    {
        var result = ImageUtility.SaveImage("/Content/Images/", 1000000, "jpg,png", image, HttpContext.Server);
    
        if (!result.Success)
        {
            var builder = new StringBuilder();
            result.Errors.ForEach(e => builder.AppendLine(e));
    
            TempData.Add("imageUploadFailure", builder.ToString());
        }
    
        return RedirectToAction("ImageUpload");
    }
    

    ImageUtility helper class:

    public static class ImageUtility
    {
        public static SaveImageResult SaveImage(string path, int maxSize, string allowedExtensions,  HttpPostedFileBase image, HttpServerUtilityBase server)
        {
            var result = new SaveImageResult { Success = false };
    
            if (image == null || image.ContentLength == 0)
            {
                result.Errors.Add("There was problem with sending image.");
                return result;
            }
    
            // Check image size
            if (image.ContentLength > maxSize)
                result.Errors.Add("Image is too big.");
    
            // Check image extension
            var extension = Path.GetExtension(image.FileName).Substring(1).ToLower();
            if (!allowedExtensions.Contains(extension))
                result.Errors.Add(string.Format("'{0}' format is not allowed.", extension));
    
            // If there are no errors save image
            if (!result.Errors.Any())
            {
                // Generate unique name for safety reasons
                var newName = Guid.NewGuid().ToString("N") + "." + extension;
                var serverPath = server.MapPath("~" + path + newName);
                image.SaveAs(serverPath);
    
                result.Success = true;
            }
    
            return result;
        }
    }
    
    public class SaveImageResult
    {
        public bool Success { get; set; }
        public List Errors { get; set; }
    
        public SaveImageResult()
        {
            Errors = new List();
        }
    }
    

    You could also tinker with response format, different file renaming or adding functionality for multiple file handling etc.

提交回复
热议问题