Upload validation

4 posts, 1 answers
  1. Stephen
    Stephen avatar
    158 posts
    Member since:
    Jan 2009

    Posted 19 May 2014 Link to this post

    Hello,

    I'm using the upload control in async mode and am passing back the empty string to signify success from my post routine.  I need to validate that the file extensions and file size are within certain specs when files are uploaded.  I have seen posts about handling this in jquery and using an alert to display the message but a) I prefer not to use alerts and b) it shows the alert but still goes to the post method (even with the e.preventDefault in place).

    I would prefer to do the checks in the post method and return a string that I can display so it would look like my usual validation.  I know that the empty string  signifies success and anything else signifies failure but when I try to trap this in onError it doesn't capture it.  I'm sure there is a way to do this but I am missing something.

    Here is my view:
    @model PASS.ViewModels.Proposals.AttachmentsViewModel
     
    <div class="editor-container">
     
        @Html.Hidden("Form_Disabled", ViewData["FormDisabled"])
     
        <p>File uploads can not exceed 1MB each and must be of the following file types: pdf, jpg, gif, png.</p>
     
        <div class="editor-label">
            @Html.Label("File(s):")
        </div>
        <div class="editor-field">
            @(Html.Kendo().Upload()
                .Name("Upload")
                .Async(async => async
                    .Save("AddAttachments", "Proposals", new { proposalID = Model.Proposal_ID })
                )
            )
        </div>
        <br class="clear" />
        <br />
        <br />
     
        @(Html.Kendo().Grid<PASS.ViewModels.Proposals.AttachmentsViewModel>()
            .Name("Attachments")
            .Columns(columns =>
            {
                columns.Bound(c => c.File_Name).ClientTemplate("<a href='" + Url.Action("LoadAttachment", "Proposals") + "/#= ID #'>" + "#= File_Name #" + "</a>").Title("File Name");
                columns.Bound(c => c.File_Size).Title("Size");
                columns.Bound(c => c.Content_Type).Title("Type");
                columns.Command(command => { command.Destroy(); }).Width(90);
            })
            .Sortable()
            .DataSource(dataSource => dataSource
                .Ajax()
                .Model(model => model.Id(c => c.ID))
                .Read(read => read.Action("GetAttachments", "Proposals", new { proposalID = Model.Proposal_ID }))
                .Destroy(destroy => destroy.Action("DeleteAttachment", "Proposals"))
            )
        )
     
        <br />
        <p>Upoaded files will not be available for viewing until they have been reviewed.</p>
     
    </div>
     
    <script type="text/javascript">
    $(document).ready(function () {
        var formDisabled = $('#Form_Disabled').val();
        if (formDisabled == "True") {
            $('#Upload').data('kendoUpload').disable();
            $('#Attachments').data('kendoGrid').bind("dataBound", function () {
                $('.k-grid-delete', '#Attachments').hide();
            })
        }
        
        $('#Upload').data('kendoUpload').bind("success", function () {
            $('#Attachments').data('kendoGrid').dataSource.read();
        })
    });
    </script>


    Here is my post method:
    [HttpPost]
    public ActionResult AddAttachments(int proposalID, IEnumerable<HttpPostedFileBase> upload)
    {
        int user_id = Convert.ToInt32(((Claim)((ClaimsIdentity)Thread.CurrentPrincipal.Identity).FindFirst(a => a.Type.Equals("UserID"))).Value);
        var return_message = "";
     
        if (CheckProposalReadAccess(user_id, proposalID))
        {
            using (var context = new PASSEntities())
            {
                foreach (var file in upload)
                {
                    if (Path.GetExtension(file.FileName) != ".pdf" || Path.GetExtension(file.FileName) != ".jpg" || Path.GetExtension(file.FileName) != ".gif" || Path.GetExtension(file.FileName) != ".png")
                    {
                        return_message = "Uploads must be one of the following file types: pdf, jpg, gif, png.";
                        break;
                    }
     
                    if (file.ContentLength > 1024)
                    {
                        return_message = "Uploads can not be larger than 1MB each.";
                        break;
                    }
     
                    Proposal_Attachments model = new Proposal_Attachments()
                    {
                        Proposal_ID = proposalID,
                        Upload_Date = DateTime.Now,
                        File_Name = Path.GetFileName(file.FileName),
                        File_Size = file.ContentLength,
                        Content_Type = file.ContentType,
                        File_Contents = new byte[file.ContentLength],
                    };
     
                    file.InputStream.Read(model.File_Contents, 0, file.ContentLength);
     
                    context.Proposal_Attachments.Add(model);
                    context.SaveChanges();
                }
     
                return Content(return_message);
            }
        }
        else
        {
            return RedirectToAction("Index");
        }
    }


    Thanks!
  2. Answer
    Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2153 posts

    Posted 20 May 2014 Link to this post

    Hello Stephen,


    Indeed if a non-empty content is returned from the save handler, the error event of the Upload widget will be triggered. You could access it through the e.XMLHttpRequest parameter.
    E.g.
    public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
    {
        ...
        return Content("my error");
    }

    function error(e) {
        var response = e.XMLHttpRequest.responseText;
    }

    Let me know if this was the information that you were looking for.

    Regards,
    Dimiter Madjarov
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  3. UI for ASP.NET MVC is VS 2017 Ready
  4. Stephen
    Stephen avatar
    158 posts
    Member since:
    Jan 2009

    Posted 20 May 2014 in reply to Dimiter Madjarov Link to this post

    That's exactly what I was looking for!  Thanks!
  5. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2153 posts

    Posted 20 May 2014 Link to this post

    Hello Stephen,


    I am glad that the issue is resolved.
    Do not hesitate to contact us again if further problems arise.

    I wish you a great day!

    Regards,
    Dimiter Madjarov
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top
UI for ASP.NET MVC is VS 2017 Ready