Search code examples
javascriptrestsharepoint-onlinedocument-library

How to get the File Type of a File in Sharepoint


I'm trying to load in documents from the Documents library in SharePoint and I want to be able to filter them by file type (Word Doc, Excel Sheet, etc.) from my application. I've figured out how to get the icon for the file type using mapToIcon, but I can't seem to find anywhere how to get the file type.

Is there any function or API call to get the file type of a file? I would prefer to not have to hard code each type based on file extension but I may need to do that.

Here is a bit of my code for reference

// data returned from an ajax call to get all documents
var results = data.d.results;

for(var i = 0; i < results.length; i++){
    // get the name of the document
    var name = results[i].Name;

    // retrieve the icon for the file type through an ajax call
    var icon;
    $.ajax({
            url: siteUrl + "/_api/web/maptoicon(filename='" + name + "',progid='',size=0)"
            /*headers*/,
            success: function(data){
                // get the icon
                icon = data.d.MapToIcon;
            },  
        });
    }

Solution

  • File_x0020_Type property of SP.ListItem resource could be utilized for that purpose.

    In case if your query (seems to be your scenario) returns files SP.FileCollection resource, file type could be retrieved like this:

    /_api/web/getfolderbyserverrelativeurl('<folder url>')/Files?$select=ListItemAllFields/File_x0020_Type&$expand=ListItemAllFields
    

    In case if your query returns list items SP.ListItemCollection resource, file type could be retrieved like this:

    /_api/web/lists/getbytitle('<list title>')/items?$select=File_x0020_Type