Suppose I have the URL to a file. How can I determine the path to the (sub)site (spweb) it is hosted on, using JavaScript.

Here are some examples. Bolded text is what I am looking for:

https://tenant.sharepoint.com/library1/file.jpg

https://tenant.sharepoint.com/sites/site1/library1/file.jpg

https://tenant.sharepoint.com/sites/site1/library1/folder1/file.jpg

https://tenant.sharepoint.com/sites/site1/library1/folder1/folder2/file.jpg

https://tenant.sharepoint.com/sites/site1/subsite1/library1/file.jpg

https://tenant.sharepoint.com/teams/site1/subsite1/library1/folder1/file.jpg

https://tenant.sharepoint.com/teams/site1/subsite1/subsite2/library1/file.jpg

有帮助吗?

解决方案

Try with following JS code

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
var owebsite;
var documentPath = "http://sharepointsite/subsite/Shared%20Documents/Forms/AllItems.aspx";
documentPath = documentPath.substring(0, documentPath.lastIndexOf('/')) + "/_api/contextinfo";
$.ajax({
    url: documentPath,
    type: "POST",
    contentType: "application/x-www-url-encoded",
    dataType: "json",
    headers: {
        "Accept": "application/json; odata=verbose",
    },
    success: function (data) {
        if (data.d) {
            var webUrl = data.d.GetContextWebInformation.WebFullUrl;
SP.SOD.executeFunc('sp.js','SP.ClientContext',function(){
            var clientContext = new SP.ClientContext(webUrl);
            owebsite = clientContext.get_web(); 
            clientContext.load(owebsite);
            clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceed),Function.createDelegate(this, this.onQueryFailed));
        });
        }
    },
    error: function (err) {
       alert(JSON.stringify(err));
    }
});

onQuerySucceed = function () {
    alert(owebsite.get_url());
};

onQueryFailed = function (sender, args) {
    alert(args.get_message());
};
</script>

其他提示

Assuming all your site/subweb have "Library1" named document library and all the files is contained in "Library1". you can try something like below:

var t ="https://tenant.sharepoint.com/sites/site1/library1/folder1/folder2/file.jpg"
t.substring(0,t.indexOf("library1")-1)

It should be SPContext.Current.Web.Url

许可以下: CC-BY-SA归因
scroll top