New to Telerik UI for ASP.NET MVC? Download free 30-day trial

Display File Location for Each Uploaded File

Environment

Product Telerik UI for ASP.NET MVC Upload
Progress Telerik UI for ASP.NET MVC version Created with the 2023.3.1114 version

Description

How can I display the location of the uploaded file as a link within the Upload component?

Solution

  1. Define an Upload component in asynchronous mode.
  2. Use the TemplateId option to define a template for rendering the files in the file list.
  3. Update the Save Action method to return the file location of the uploaded file.
  4. Subscribe to the Success event to intercept the received file location from the server. Select the anchor tag within the file template with jQuery and update the href attribute with the respective file location.
    @(Html.Kendo().Upload()
        .Name("files")
        .TemplateId("fileTemplate")
        .Async(a => a
            .Save("Async_Save", "Home")
            .Remove("Remove", "Home")
            .AutoUpload(true)
        )
        .Events(ev => ev.Success("onSuccess"))
    )

    <script id="fileTemplate" type="text/x-kendo-template">
        <span class="k-progress"></span>
        <span class="k-file-group-wrapper">
            <span class="k-file-group k-icon k-i-file-image"></span>
            <span class="k-file-state"></span>
        </span>
        <span class="k-file-name-size-wrapper">
            <span class="k-file-name"><a href="" target="_blank">#=data.name#</a></span>
        </span>
        <strong class="k-upload-status">
            <button type="button" class="k-button k-icon-button k-button-md k-rounded-md k-button-flat k-button-flat-base k-upload-action"><span class="k-button-icon k-icon k-i-close k-i-x" title="Remove"></span>
            </button>
        </strong>
    </script>
    <script>
        function onSuccess(e) {
            var uploadedFileName = e.files[0].name;
            var fileLocation = e.response.location;
            var fileLocationLinks = $(".k-file-name a");
            $.each(fileLocationLinks, function () {
                if ($(this).text() == uploadedFileName) {
                    $(this).attr("href", fileLocation);
                }
            });
        }
    </script>
    public ActionResult Async_Save(IEnumerable<HttpPostedFileBase> files)
    {
        string filesLocation = null;
        if (files != null)
        {
            foreach (var file in files)
            {
                var fileName = Path.GetFileName(file.FileName);
                var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                filesLocation = physicalPath;
                file.SaveAs(physicalPath);
            }
        }
        return Json(new { location = filesLocation }, JsonRequestBehavior.AllowGet);
    }

More ASP.NET MVC Upload Resources

See Also

In this article