Friday, December 27, 2019

Get attachments in list items JSlink (REST API)

In this article I’ll give an example of how to use REST API and JSlink to make a request to attachments in list items which will be useful for working with current and future development projects on the MS SharePoint server (2013, 2016, 2019, Online) platform.
function AttachmentFiledTemplate(ctx){ 
    var listItem = ctx.CurrentItem;
    var listTitle = ctx.ListTitle;
    var spHostUrl = ctx.HttpRoot;
    var itemId = listItem.ID;
    context = ctx;
    var queryUrl = spHostUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items('" + itemId + "')/AttachmentFiles";
    $.ajax({
    url: queryUrl,
        headers: { 
            "accept": "application/json; odata=verbose",
        },
        method: "GET",
         success: function(data){
            $.each(data.d.results, function(){
                //url attachments in list Items
                var attachmenturl = this.ServerRelativeUrl;
                console.log(attachmenturl);
            })
        },
        error: function ajaxError(response){
        alert(response.status + ' ' + response.statusText);
        }
    });
}

We implement using the REST API the name of the attached files in the list items (Example):
(function () {
    var linkFiledContext = {};
    linkFiledContext.Templates = {};
    linkFiledContext.Templates.Fields = {    
        "Attachments": { "View": AttachmentsFiledTemplate }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext);

})();

function AttachmentsFiledTemplate(ctx) {
    var itemId = ctx.CurrentItem.ID;
    var listName = ctx.ListTitle;       
    return getAttachments(listName, itemId);
}

function getAttachments(listName,itemId) {  
    var url = _spPageContextInfo.webAbsoluteUrl;
    var requestUri = url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles";
    var str = "";
    $.ajax({
        url: requestUri,
        type: "GET",
        headers: { "ACCEPT": "application/json;odata=verbose" },
        async: false,
        success: function (data) {
            for (var i = 0; i < data.d.results.length; i++) {
                str += "<a href='" + data.d.results[i].ServerRelativeUrl + "'>" + data.d.results[i].FileName + "</a>";
                if (i != data.d.results.length - 1) {
                    str += "<br/>";
                }                
            }          
        },
        error: function (err) {
        }
    });
    return str;
}

Result:
Happy Coding!

No comments:

Post a Comment