koltyakov / gosip

⚡️ SharePoint SDK for Go
https://go.spflow.com
MIT License
145 stars 33 forks source link

how to list files under a folder #36

Closed tlightsky closed 3 years ago

tlightsky commented 3 years ago

I tried this:

    itemsResp, err := list.Items().
        Select("*").          // OData $select modifier, limit what props are retrieved
        OrderBy("Id", false). // OData $orderby modifier, defines sort order
        Get() // Finalizes API constructor and sends a response

but it seems the Title filed don't contain the file name

koltyakov commented 3 years ago

Hi @tlightsky,

In SharePoint API, the document library and list are the same. But list item and file are different things.

However, it's possible getting files info querying a library as a list. An expand for File object and selecting File/* exposes file properties, including the Name along with many others.

Filtering files by a folder is possible with .Filter("FileDirRef eq '/sites/site/Folder Path/Sub Folder'").

libRootRelativePath := "/sites/site/Shared Documents"

list := sp.Web().GetList(libRootRelativePath)

items, err := list.Items().
    Select("Id,File/Name,File/ServerRelativeUrl").
    Filter(fmt.Sprintf("FileDirRef eq '%s/Sub Folder' and FSObjType eq 0", libRootRelativePath)).
    Expand("File").
    Get()

if err != nil {
    log.Fatal(err)
}

for _, i := range items.ToMap() {
    fmt.Printf("%v#\n", i)
}

However, this can fail with throttling for large document libraries. And operating via Folders/Files methods is preferable in many scenarios. With Folders/Files methods you'd face the reverse question - "How to get item's props?" - ListItemAllFields prop should be expanded and selected.

folder := sp.Web().GetFolder("Shared Documents/Sub Folder")

files, err := folder.Files().
    Select("*,ListItemAllFields/*").
    Expand("ListItemAllFields").
    Get()

if err != nil {
    log.Fatal(err)
}

for _, f := range files.Data() {
    fmt.Printf("%s\n", f.Normalized())
}
tlightsky commented 3 years ago

thanks for your detailed explain, really saved my day @koltyakov

koltyakov commented 3 years ago

Great!