javascript 从文档库中获取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29699830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:56:16  来源:igfitidea点击:

Get file name from document library

javascriptsharepointsharepoint-2013sharepoint-clientobject

提问by Mahatma Aladdin

I have a document library named DocLibrary. Inside that, I have created few folders. Each folder have 3 other folder. Inside that, I store the specific files. Example: DocLibrary > NF1> Communications, where DocLibrary is the document library, NF1 is the folder inside DocLibrary and Communications is the folder inside NF1.

我有一个名为DocLibrary的文档库。在里面,我创建了几个文件夹。每个文件夹有3个其他文件夹。在里面,我存储了特定的文件。示例: DocLibrary > NF1> Communications,其中 DocLibrary 是文档库,NF1 是 DocLibrary 中的文件夹, Communications 是 NF1 中的文件夹。

Now I want to give the download link to a particular file inside the Communications folder sorted by modified date. I am facing problem on how to goto Communications folder and then select file name.

现在我想提供按修改日期排序的 Communications 文件夹中特定文件的下载链接。我在如何转到 Communications 文件夹然后选择文件名方面遇到问题。

I am using java-script for that.

我为此使用了 java 脚本。

Right now I am using the below code. But I am completely new to this and have limited ideas on How to approach. Kindly help.

现在我正在使用下面的代码。但是我对此完全陌生,并且对如何处理的想法有限。请帮助。

function test1()
{
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle('DocLibrary');

    var query = SP.CamlQuery.createAllItemsQuery();
    query.set_folderServerRelativeUrl('/DocLibrary/NF1/Communications/');
    allItems = list.getItems(query);
    alert('hi');
    context.load(allItems);

    context.executeQueryAsync(Function.createDelegate(this, this.success),   Function.createDelegate(this, this.failed));
}

function success()
{
    var fileUrls = '';
    var ListEnumerator = this.allItems.getEnumerator();
    while(ListEnumerator.moveNext())
    {
        var currentItem = ListEnumerator.get_current();
        var _contentType = currentItem.get_contentType();
        if(_contentType.get_name() != 'Folder')
        {
            var File = currentItem.get_file();
            if(File != null)
            {
                fileUrls += File.get_serverRelativeUrl() + '\n';
            }
        }
    }
    alert(fileUrls);
}
function failed(sender, args) {
    alert('failed. Message:' + args.get_message());
}

回答by Daniel B

Since you are using JavaScript, I'd suggest that you make a GETrequest to the SharePoint REST API to get the information you want.

由于您使用的是 JavaScript,我建议您GET向 SharePoint REST API 发出请求以获取所需信息。

You can access your document library and it's folder simply by making a request to

您只需发出请求即可访问您的文档库及其文件夹

http://siteUrl/_api/web/getfolderbyserverrelativeurl('Documents/NF1/Communications')/files?$orderby=TimeLastModified%20desc

http://siteUrl/_api/web/getfolderbyserverrelativeurl('Documents/NF1/Communications')/files?$orderby=TimeLastModified%20desc

If you navigate to the above URL in your browser, substituting siteUrlwith your sites real URL, you'll get a response back in XML format.

如果您在浏览器中导航到上述 URL,siteUrl用您的站点的真实 URL替换,您将得到 XML 格式的响应。



Requesting from JavaScript

从 JavaScript 请求

Note that this method requires jQuery to work, otherwise you would have to make an XMLHttpRequestto the server.

请注意,此方法需要 jQuery 才能工作,否则您必须对XMLHttpRequest服务器进行处理。

To make the request from JavaScript, an $.ajax()is very straightforward.

要从 JavaScript 发出请求, an$.ajax()非常简单。

$.ajax({
    url: _spPageContextInfo.siteAbsoluteUrl + "_api/web/getfolderbyserverrelativeurl('Documents/NF1/Communications')/files?$orderby=TimeLastModified%20desc",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (result) {
        //Do something with the result here!
        $.each(result.d.results, function(i, item){
            console.log("The URL to the file is: " + item.__metadata.uri);
        });
    },
    error: function (error) {
        //Ouch, an error occured with the request
        //Don't forget to handle the error in some way!
    }
});

This will return an array of all the files in your folder, sorted by the field TimeLastModified, where the one with the latest modification time on the top index. The URL to each file can be accessed through the __metadata.uriproperty on each object in the array.

这将返回文件夹中所有文件的数组,按字段排序TimeLastModified,其中顶部索引具有最新修改时间的文件。可以通过__metadata.uri数组中每个对象的属性访问每个文件的 URL 。

In the above code sample, I iterate through all the files using jQuery $.each()function, and prints the URL of the file to the console. Depending on what you want to do with the URL, you'll have to write your custom code there.

在上面的代码示例中,我使用 jQuery$.each()函数遍历所有文件,并将文件的 URL 打印到控制台。根据您想对 URL 做什么,您必须在那里编写自定义代码。

You can reference MSDN - Files and folders REST API referenceif you want to explore the REST API further.

如果您想进一步探索 REST API,您可以参考MSDN - 文件和文件夹 REST API 参考

回答by Vadim Gremyachev

Some recommendations

一些建议

1) You could construct the query that returns only Files and sorted by modified date:

1)您可以构建仅返回文件并按修改日期排序的查询:

<View>
   <Query>
     <Where>
       <Eq><FieldRef Name="FSObjType" /><Value Type="Integer">0</Value></Eq>                                                                                                                                                    
     </Where>
     <OrderBy>
       <FieldRef Name="Modified" Ascending="FALSE" />
     </OrderBy>
   </Query>
</View>

2) From performance perspective since you are interested in File properties, you could specify explicitly what properties to retrieve, for example:

2)从性能角度来看,由于您对文件属性感兴趣,您可以明确指定要检索的属性,例如:

context.load(items,'Include(File.ServerRelativeUrl)'); // retrieve File.ServerRelativeUrl

Modified example

修改示例

function getFiles(listTitle,folderUrl,success,failed)
{
    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(listTitle);
    var createItemsQuery = function(folderUrl){
       var qry = new SP.CamlQuery();
       qry.set_viewXml('<View><Query><Where><Eq><FieldRef Name="FSObjType" /><Value Type="Integer">0</Value></Eq></Where><OrderBy><FieldRef Name="Modified" Ascending="FALSE" /></OrderBy></Query></View>');
       qry.set_folderServerRelativeUrl(folderUrl);
       return qry;
    };
    var items = list.getItems(createItemsQuery(folderUrl));
    context.load(items,'Include(File.ServerRelativeUrl)');
    context.executeQueryAsync(
       function(){
          success(items)
       },
       failed);
}

Usage

用法

var listTitle = 'DocLibrary';
var folderUrl = '/DocLibrary/NF1/Communications'; //format: /[site]/[library]/[folder]
getFiles(listTitle,folderUrl,
   function(items)
   { 
       var fileUrls = []; 
       items.get_data().forEach(function(item){
           var file = item.get_file();
           fileUrls.push(file.get_serverRelativeUrl());
       });
       var result = fileUrls.join(',');   
       console.log(result);
   },
   function(sender, args) {
        console.log('Message:' + args.get_message());
   });