问题
I'm trying to upload an attachment i get from Outlook to a folder inside a SharePoint document library. I am Following the docs: https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http#http-request-to-upload-a-new-file
fetch(`https://graph.microsoft.com/v1.0/sites/${siteId}/drive/items/${parentId}:/${attachment.name}:/content`, {
method: 'PUT',
mode: 'cors',
headers: new Headers({
'Authorization': `Bearer ${accesToken}`,
'Content-Type': 'text/plain'
}),
body: attachment.contentBytes
})
All I get is an error with code: -1, Microsoft.SharePoint.Client.InvalidClientQueryException
I've tried setting the body of the fetch request as a simple string such as "hello world" with testing purposes and still get the same error.
Any ideas?
Thx in advance
[EDIT] I suspect I'm not building the URL right. I haven't found the documentation for the parameter:
- {item-id} I'm assuming this ID is the folder's
parentReference.siteId
attribute.
Is that right?
回答1:
Allright, so after some testing with the Microsoft Graph Explorer, I've found that the easiest way to upload a file to a SharePoint folder living inside a document library (distinct to the root document library) is to deal with it as a drive using the endpoint:
/drives/{drive-id}/items/{parent-id}:/{filename}:/content
(https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http#http-request-to-upload-a-new-file)
In order to get the document library's drive-id, you can append to the graph query the odata parameter $expand=drive like:
`https://graph.microsoft.com/v1.0/sites/${siteId}/lists?$expand=drive`
Then, alongside other attributes of the targetted document library, you will find the "drive" object, which holds the drive-id associated to the document library you want to upload the file to. So, you would make the PUT request like:
fetch(`https://graph.microsoft.com/v1.0/drives/${libraryDriveId}/items/root:/${folderDisplayName}/${nameOfFile}:/content`, {
method: 'PUT',
mode: 'cors',
headers: new Headers({
'Authorization': `Bearer ${accesToken}`,
'Content-Type': 'text/plain'
}),
body: BINARY_STREAM_OF_DATA
}).then( (response) => {
if (!response.ok) return response.json().then((json) => {throw json});
return response.json();
}).then( (json) => {
//do whatever
}).catch( (err) => {
console.error(err);
})
libraryDriv
libraryDriveId
comes from thehttps://graph.microsoft.com/v1.0/sites/${siteId}/lists?$expand=drive
request/root:/${folderDisplayName}
means that the folder you are targetting inside the document library lives under "root:" (the root of the document library) followed by thedisplayName
of the folder you want to upload the file tonameOfFile
is the name of the file you want to upload
来源:https://stackoverflow.com/questions/59824303/unable-to-upload-new-file-4mb-to-sharepoint-ms-graph-api