'Get file name from document library

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.

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.

I am using java-script for that.

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());
}


Solution 1:[1]

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

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

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


Requesting from JavaScript

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

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

$.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.uri property on each object in the array.

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.

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

Solution 2:[2]

Some recommendations

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

<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:

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());
   });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel B
Solution 2 Vadim Gremyachev