【问题标题】:Unable to upload new file (<4MB) to SharePoint (ms graph api)无法将新文件 (<4MB) 上传到 SharePoint (ms graph api)
【发布时间】:2020-01-20 13:26:58
【问题描述】:

我正在尝试将从 Outlook 获取的附件上传到 SharePoint 文档库中的文件夹。 我正在关注文档: 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
    })

我得到的只是代码错误:-1, Microsoft.SharePoint.Client.InvalidClientQueryException

出于测试目的,我尝试将获取请求的主体设置为简单的字符串,例如“hello world”,但仍然得到相同的错误。

有什么想法吗?

提前谢谢


[编辑] 我怀疑我没有正确构建 URL。 我还没有找到参数的文档:

  • {item-id} 我假设这个 ID 是文件夹的 parentReference.siteId 属性。

是吗?

【问题讨论】:

  • 你得到这份工作了吗?我总是收到错误Entity only allows writes with a JSON Content-Type header.
  • 是的。看看我自己的回复:)

标签: microsoft-graph-api microsoft-graph-files


【解决方案1】:

好的,所以在使用 Microsoft Graph Explorer 进行一些测试后,我发现将文件上传到位于文档库(与根文档库不同)中的 SharePoint 文件夹的最简单方法是将其处理为使用端点的驱动器:

/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)

为了获取文档库的drive-id,您可以将odata 参数$expand=drive 附加到图形查询中,例如:

`https://graph.microsoft.com/v1.0/sites/${siteId}/lists?$expand=drive`

然后,除了目标文档库的其他属性,您将找到“驱动器”对象,该对象包含与您要将文件上传到的文档库关联的 drive-id。因此,您可以像这样发出 PUT 请求:


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 来自https://graph.microsoft.com/v1.0/sites/${siteId}/lists?$expand=drive 请求
  • /root:/${folderDisplayName} 表示您在文档库中定位的文件夹位于“root:”(文档库的根目录)下,后跟您要将文件上传到的文件夹的 displayName
  • nameOfFile是你要上传的文件名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多