4

I want to Get all files inside a folder in a library using REST in SharePoint.

I have tried this code

var folderUrl = '/attachment/test/1';
var url = _spPageContextInfo.webServerRelativeUrl + "/_api/Web/GetFolderByServerRelativeUrl('" + folderUrl + "')?$expand=Folders,Files";

$.getJSON(url,function(data,status,xhr){

    for(var i = 0; i < data.Files.length;i++){
        console.log(data.Files[i].Name);    
    }

    for(var i = 0; i < data.Folders.length;i++){
        console.log(data.Folders[i].Name);    
    }
});
  • what's the issue in the above code? – Mohamed El-Qassas MVP Aug 22 '17 at 18:09
  • 1
    Are you trying to get all attachments of a list item? – Amal Hashim Aug 22 '17 at 18:14
  • it is actually a library name attachment and within it it has folder test and then sub folder 1 and....i am trying to retrieve all the file under this 1 folder...the above code I found in this site itself but I don't know where I am going wrong – guest Aug 23 '17 at 7:57
3

Two things seems wrong in your code,

  1. Folder Url should be 'attachment/test/1'

  2. Syntax for reading response should be data.d.Files.results[i].Name

Try below code. ( Tested & Working )

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        getFilesFolders();
    });


    function getFilesFolders() {
        var folderUrl = 'attachment/test/1';
        var webUrl = _spPageContextInfo.webAbsoluteUrl;
        var requestHeaders = { "accept": "application/json;odata=verbose" };
        $.ajax({
            url: webUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')?$expand=Folders,Files",
            contentType: "application/json;odata=verbose",
            headers: requestHeaders,
            success: onSuccess,
            async: false,
            error: onError
        }); function onSuccess(data, request) {
            for (var i = 0; i < data.d.Files.results.length; i++)
            {
                console.log(data.d.Files.results[i].Name);
            }
            for (var i = 0; i < data.d.Folders.results.length; i++) {
                console.log(data.d.Folders.results[i].Name);
            }    

        } function onError(error) {
            alert("Error occurred.");
        }
    }
</script>
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.