3

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 Answers 3

8

You will need to validate with javascript, here is a sample

function onSelect(e) {
    if (e.files[0].size > 256000) {
        alert('The file size is too large for upload');
        e.preventDefault();
        return false;
    }
    // Array with information about the uploaded files
    var files = e.files;
    var ext = $('#logo').val().split('.').pop().toLowerCase();
    if ($.inArray(ext, ['gif', 'jpeg', 'jpg', 'png', 'tif', 'pdf']) == -1) {
        alert('This type of file is restricted from being uploaded due to security reasons');
        e.preventDefault();
        return false;
    } 
    return true;
}

this says the file must be no greater than 256K and allows only gif, jpg, jpeg, tif, png and pdf. Just change 256000 to 5000000 and your specific file type

I'm using this in MVC 3 in a razor view with the Telerik upload control. You can use with a standard upload input as well, just fire this event on selection or before committing

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, I've been using this code for the past year and it works like a charm
Thank you but one more question how i can call onSelect() function? like this: <input type="file" name="file" id="file_uploader" onselect="OnSelect()" />
try the onchange event onchange = onSelect(this);
@AlfalfaStrange I've tried your code with a standard <input type="file"> control on a Razor page. I fire the onSelect function via onchange when a file is selected but it's failing on the first line. The error I'm getting is "e.files is undefined". Any ideas?
5

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" }))
{                  
    <legend>Add Image</legend>

    <label>Image</label>
    <input name="image" type="file" value=""/>
    <br/>

    <input type="submit" value="Send"/>
}

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<string> Errors { get; set; }

    public SaveImageResult()
    {
        Errors = new List<string>();
    }
}

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

Comments

2

This is just to specify file types to be accepted: MSvisualstudio2010.

In your View(.cshtml):

ATTACHMENT:<input type="file" name="file" id="file" accept=".PNG,.TXT,.JPG,.BMP" />

Just specify the formats you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.