使用Sharepoint 2013 REST Api / CSOM检索发布图像字段

问题描述 投票:9回答:3

我们使用Sharepoint 2013 REST API从Sharepoint获取所有新闻项。我们制作了一个自定义ContentType“Newsitem”,其中包含一些属性,包括发布图像字段。

  var contentTypeId = "0x01100018B03AC7E8312648AEA00851DEDBCAF802";
  var standardUri = "https://examplesite.com/blog/_api/lists/getbytitle('Messages')/items?$top=7&$filter=startswith(ContentTypeId,'" + contentTypeId + "')";
  var selectiveUri = "https://examplesite.com/blog/_api/lists/getbytitle('Messages')/items?$top=7&$filter=startswith(ContentTypeId,'" + contentTypeId + "')&$Select=Title,Teaser,Body,ShowAt,TeaserImg";

使用standardUri进行我的REST调用,我检索所有属性但没有TeaserImg。明确选择TeaserImg会使呼叫失败。

为什么我找不到TeaserImg,这不是可能的Sharepoint 2013 REST Api,我应该使用CSOM吗?

sharepoint sharepoint-2013 csom
3个回答
14
投票

使用List Item Collection端点检索Publishing Image字段似乎不可能。

有一种解决方法,可以通过SharePoint REST端点使用ListItem.FieldValuesAsHtml属性检索发布字段,如下所示

限制:它需要执行两个请求。

如何使用SharePoint 2013 REST检索发布字段

function getJson(endpointUri, success, error) 
{    
    $.ajax({       
       url: endpointUri,   
       type: "GET",   
       processData: false,  
       contentType: "application/json;odata=verbose",
       headers: {   
          "Accept": "application/json;odata=verbose"
       }, 
       success: success,
       error: error
    });
}


function getPublishingPage(webUrl,listName,listItemId,publishingProperties, success, failure) 
{
    var itemUri =  webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + listItemId + ")";  
    getJson(itemUri,
       function(data){
           var pageItem = data.d;

           var selectProperties = [];  
           for(var idx in publishingProperties){
               if(!pageItem.hasOwnProperty(publishingProperties[idx])){
                   selectProperties.push(publishingProperties[idx]);
               }
           }
           if(selectProperties.length > 0) {
              //construct an additional query 
              var query = '/FieldValuesAsHtml?$select=' + selectProperties.join(',');
              var endpointUri = pageItem['__metadata'].uri + query;
              getJson(endpointUri,
                 function(data){
                    for(var property in data.d){
                       if(property == "__metadata") continue; 
                       pageItem[property] = data.d[property];   
                    }
                    success(pageItem);  
                 },
                 failure);
           } 
           else {
              success(pageItem);
           }   
        },
       failure);
}

用法

以下示例演示如何检索页面字段,包括发布字段,例如PublishingRollupImage

getPublishingPage(_spPageContextInfo.webAbsoluteUrl,'Pages',3,['PublishingRollupImage','PublishingPageImage'],printPageDetails,logError);

function printPageDetails(pageItem)
{
    console.log('Page Content: ' + pageItem.PublishingPageContent);
    console.log('Page Title: ' + pageItem.Title);
    console.log('Page Rollup Image ' + pageItem.PublishingRollupImage);
}

function logError(error){
    console.log(JSON.stringify(error));
}

这里最好的解决方案可能是利用CSOM

function getListItems(listTitle,success,error)
{
   var ctx = SP.ClientContext.get_current();
   var list = ctx.get_web().get_lists().getByTitle(listTitle);
   var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
   ctx.load(items);
   ctx.executeQueryAsync(function() {
       success(items);
   },error);
}



getListItems('Pages',printPageItemsDetails,logError);

function printPageItemsDetails(pageItems)
{
    for(var i = 0; i < pageItems.get_count();i++) {
        var pageItem = pageItems.getItemAtIndex(i);
        console.log(pageItem.get_fieldValues()['PublishingPageContent']);
        console.log(pageItem.get_fieldValues()['PublishingRollupImage']);
    }
}

6
投票

不幸的是,发布图像字段在技术上不能通过REST返回(至少,根据this article)。

但是我发现(使用Advanced REST client)你可以通过发出两个请求来实际检索发布图像字段的html。一个用于检索您尝试获取发布图像的列表项,另一个用于通过返回结果的FieldValuesAsHtml属性检索发布图像html。

getPublishingImage(listname, id){
    var publishingImage = '';

    $.ajax({
        url:        _spPageContextInfowebroot.webAbsoluteUrl + '/_api/web/lists/getbytitle(\'' + listname + '\')/items(' + id + ')',
        method:     'GET',
        headers:    {
            Accept:     'application/json; odata=verbose'
        },
        success:    function(data, request){
            // List item retrieved. Fetch the Publishing Image.
            var publishingImageUri = data.d.0.FieldValuesAsHtml.__deferred.uri;

            // Query SharePoint
            $.ajax({
                url:        publishingImageUri,
                method:     'GET',
                headers:    {
                    Accept:     'application/json; odata=verbose'
                },
                success:    function(data, request){
                    publishingImage = data.d.Image;
                }
            });
        }
    });

    // Return the Publishing Image html
    return publishingImage;
};

虽然不理想,但至少使用html,您可以使用jQuery或其他方法从html元素中提取图像uri。或者您可以简单地将元素插入DOM中。

希望这可以帮助!


0
投票
function LoadArticle(item) {
  return GetPublishingPageImage(item, ["DCCAIContentImage"]).then(function(
    pub
  ) {
    for (var property in pub.d) {
      if (property == "__metadata") continue;
      item.DCCAIContentImage(pub.d[property]);
    }
  });
}

function GetPublishingPageImage(curItem, publishingProperties) {
  var query = "/FieldValuesAsHtml?$select=" + publishingProperties;

  //debugger;
  var endpointUri = curItem["__metadata"].uri + query;
  //      var endpointUri = curItem.__metadata().uri + query;

  return $.ajax({
    url: endpointUri,
    type: "GET",
    processData: false,
    contentType: "application/json;odata=verbose",
    headers: {
      Accept: "application/json;odata=verbose"
    }
  }).then(function(response) {
    return response;
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.