使用Javascript以编程方式访问sharepoint中的文档集中的文件

时间:2015-04-05 20:57:02

标签: javascript sharepoint

我想访问文档库中特定文档集中的文件。

到目前为止,我能够使用JSOM获取特定的文档集名称和ID,如下所示。 如何阅读文档集中的所有文件



<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
 
<script type="text/javascript">
   ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js");
 
    function MainFunction() {
        var clientContext = new SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('Planner Session');
 
        var camlQuery = new SP.CamlQuery(); //initiate the query object
 
        camlQuery.set_viewXml('<View><Query><Where><Lt><FieldRef Name="ID" /><Value Type="Counter">3</Value></Lt></Where><OrderBy><FieldRef Name="ID" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
 
        this.collListItem = oList.getItems(camlQuery);
 
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded),
            Function.createDelegate(this, this.onQueryFailed)
        );
    }
 
    function onQuerySucceeded(sender, args) {
        var DocSet = "";
        var listItemEnum = collListItem.getEnumerator();
 
        while (listItemEnum.moveNext()) {
            var oListItem = listItemEnum.get_current();
            DocSet += '\n\nID: ' + oListItem.get_id() + '\nName: ' + oListItem.get_item('FileLeafRef');
        }
 // Here i would like to get the file inside the documentSet 
        alert(DocSet.toString());
    }
 
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() +
            '\n' + args.get_stackTrace());
    }
</script>​
 
<input type="button" value="Get Products" onclick="MainFunction()"/>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

如何通过SharePoint CSOM获取文档集的文件

假设以下结构:

Documents (library)
    |
    2013 (Document set)

基于查询的方法

以下示例演示如何使用CAML query返回位于文档集中的文件:

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

关键点:

用法

var listTitle = 'Documents';
var docSetUrl = '/Documents/2013';  
getListItems(listTitle,docSetUrl, 
     function(items){
        for(var i = 0; i < items.get_count();i++) {
            var file = items.get_item(i).get_file();
            console.log(file.get_title());
        }
     },
     function logError(sender,args) 
     {
        console.log(args.get_message());
     });

使用SP.Web.getFolderByServerRelativeUrl方法

使用SP.Web.getFolderByServerRelativeUrl Method将文档集对象置于指定的服务器相对URL,然后SP.Folder.files property获取文档集中包含的所有文件的集合

完整示例:

function getFiles(folderUrl,success,error)
{
    var ctx = SP.ClientContext.get_current();
    var files = ctx.get_web().getFolderByServerRelativeUrl(folderUrl).get_files();
    ctx.load(files);
    ctx.executeQueryAsync(
      function() {
          success(files); 
      },
      error);
}

用法

var docSetUrl = '/Documents/2013';  //<-- '2013'
getFiles(docSetUrl, 
     function(files){
        for(var i = 0; i < files.get_count();i++) {
            var file = files.get_item(i);
            console.log(file.get_title());
        }
     },
     function logError(sender,args) 
     {
        console.log(args.get_message());
     });

答案 1 :(得分:0)

请找到执行以下操作的完整代码 1.根据我的条件获取所需的docset 2.通过检查自定义列

中的值来获取该特定文档集中的所有文件

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
 
<script type="text/javascript">
   ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js");
 
    function MainFunction() {
	var currentListID = getQueryStringValue("List");
	
        var clientContext = new SP.ClientContext.get_current();

	this.ListId = "{" + currentListID + "}";
	var oList = clientContext.get_web().get_lists().getById(ListId);
 
        var camlQuery = new SP.CamlQuery(); //initiate the query object
		var currentDocSetID = getQueryStringValue("ID");
        camlQuery.set_viewXml('<View><Query><Where><Lt><FieldRef Name="ID" /><Value Type="Counter">' + currentDocSetID + '</Value></Lt></Where><OrderBy><FieldRef Name="ID" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
 
        this.collListItem = oList.getItems(camlQuery);
 
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded),
            Function.createDelegate(this, this.onQueryFailed)
        );
    }
 
    function onQuerySucceeded(sender, args) {
        var DocSet = "";
        var listItemEnum = collListItem.getEnumerator();
 
        while (listItemEnum.moveNext()) {
            var oListItem = listItemEnum.get_current();
            DocSet += oListItem.get_item('FileLeafRef');
        }
		// Here i would like to get the file inside the documentSet 
       // alert(DocSet.toString());

		var fsoType = oListItem.get_fileSystemObjectType(); 
        
        if(oListItem.FileSystemObjectType == SP.FileSystemObjectType.Folder)
		{
           
		//var folderUrl =  "/" + listName + "/" + DocSet.toString();

		var RawFolderUrl = getQueryStringValue("RootFolder");

		var pos = RawFolderUrl.lastIndexOf('/');

		var folderUrl = RawFolderUrl.substring(0,pos) + "/" + DocSet.toString();

		GetFilesFromFolder(folderUrl);

		}
		
    }
	
	
    var allItems;
    function GetFilesFromFolder(folderUrl)
    {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        var list = web.get_lists().getById(ListId);
        // Use createAllItemsQuery to get items inside subfolders as well. Otherwise use new SP.CamlQuery() to get items from a single folder only
        var query = SP.CamlQuery.createAllItemsQuery();
        query.set_folderServerRelativeUrl(folderUrl);
        allItems = list.getItems(query);
          context.load(allItems, 'Include(File, FileSystemObjectType,Document_x0020_Type,Title)');
        context.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), Function.createDelegate(this, this.OnFailure));
    }
    function OnSuccess()
    {                                              
        var listItemEnumerator = allItems.getEnumerator();
        while(listItemEnumerator.moveNext())
        {
            var currentItem = listItemEnumerator.get_current();                                                                                                                     
            if(currentItem.get_fileSystemObjectType() == "0")
            {
                var file = currentItem.get_file();
                if(file != null && currentItem.get_item("Document_x0020_Type") == "03. Minutes")
                {
                   // alert('File Name: ' + file.get_name() + '\n' + 'File Url: ' + file.get_serverRelativeUrl());  
 		   // alert(currentItem.get_item("Title"));   
 		    var link = document.getElementById("prvMinutes");
  	            link.href= file.get_serverRelativeUrl();  
                   // link.innerHTML = currentItem.get_item("Title");                                                     
		     link.innerHTML = file.get_name();
                }
		
            }
        }                                              
    }


    function OnFailure(sender, args) {
        alert("Failed. Message:" + args.get_message());
    }
 
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() +
            '\n' + args.get_stackTrace());
    }

	function getQueryStringValue (key) {  
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace

(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}
</script>
<a id="prvMinutes" href="#" target="_blank"> </a>