Create document set with REST API in SharePoint Framework
-
05-02-2021 - |
Вопрос
I'm looking for a way to create a document set in my document library from within SPFx web part
. I'm using @microsoft/sp-http
module to create HTTP requests.
Do I need to manually create some content types inside SP?
How can I determine content type ID of the document set?
What data do I need to put in the head and body of the request?
Решение
You need to make 2 HTTP requests to get it working.
1st request will get the content type Id of the document set content type present in the SharePoint document library.
2nd will make use of the content type id and then post the payload containing document set name and other necessary properties to the doc lib which will create the document set.
If you already know the content type id or you are sure that it wont change, then you can skip and "hard-code" it in your code.
The code to create it is as below, do make the changes as necessary as per your list names :
let ctEndpointUrl = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Documents')/contenttypes?$select=Id&$filter=Name eq 'Document Set'`
this.context.spHttpClient.get(ctEndpointUrl,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=verbose',
'odata-version': ''
}
}).then((response: SPHttpClientResponse) => {
return response.json();
}).then(ct => {
// path of the SharePoint list
let listUrl = `${this.context.pageContext.web.absoluteUrl}/Shared Documents`;
//name of the document set that you want to create
let documentSetname = "DocumentSetName101";
// content type id of Document set present in sharepoint list
// you can hard-code this and skip the above HTTP request if you know the content type id before hand
let contentTypeId = ct.d.results[0]["Id"]["StringValue"];
let options: ISPHttpClientOptions = {
method: "POST",
body: JSON.stringify(
{ 'Title' : documentSetname , 'Path' : listUrl }),
headers:
{ "content-type": "application/json;odata=verbose",
"accept": "application/json;odata=verbose",
"slug": `${listUrl}/${documentSetname}|${contentTypeId}`
}
};
// using the old _vti_bin/listdata.svc endpoint which expects the list's display name
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_vti_bin/listdata.svc/Documents`,
SPHttpClient.configurations.v1, options).then((d:SPHttpClientResponse) => {
d.json().then(res => {
// success
console.log(res);
})
}).catch(e => {
// error
console.log(e);
});
});
References - Creating document sets using PnP JS