使用 GraphAPI 将文件上传到 SharePoint 网站

问题描述 投票:0回答:1

我正在尝试创建一个 Outlook 加载项,让用户可以选择将电子邮件中的部分或全部附件上传到他们有权访问的 SharePoint 网站。 我这样做的方法是从 Office.context (messageId) API 获取 itemId,使用它调用 Graph API 端点附件,然后过滤响应选择我想要的附件,然后上传它。 但是,正在上传的文件是空/损坏的文件,我是否误解了端点的工作原理?

const attachments = await client.api(`/me/messages/${messageId}/attachments`).get();

      const files = attachments.value.map((file: any) => ({
        name: file.name,
        attachmentId: file.id,
        content: file.contentBytes,
        size: file.size,
        contentType: file.contentType,
        selected: false,
      }));


const selectedFiles = attachedFiles.filter((file) => file.selected);
    for (const file of selectedFiles) {
      try {
        const response = await client
          .api(`/sites/${siteId}/drive/items/${path}:/${file.name}:/content`)
          .header("Content-Type", "application/" + file.contentType)
          .header("@odata.type", "#microsoft.graph.fileAttachment")
          .put(file.content);`
typescript sharepoint microsoft-graph-api
1个回答
0
投票

您可以参考以下代码上传文件

public static void UploadFile(ClientContext context,string uploadFolderUrl, string uploadFilePath)  
{  
    var fileCreationInfo = new FileCreationInformation  
    {  
            Content = System.IO.File.ReadAllBytes(uploadFilePath),  
            Overwrite = true,  
            Url = Path.GetFileName(uploadFilePath)  
    };  
    var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);  
    var uploadFile = targetFolder.Files.Add(fileCreationInfo);  
    context.Load(uploadFile);  
    context.ExecuteQuery();  
}  
  
using (var ctx = new ClientContext(webUri))  
{  
     ctx.Credentials = credentials;  
  
     UploadFile(ctx,"LibName/FolderName/Sub Folder Name/Sub Sub Folder Name/Sub Sub Sub Folder Name",filePath);     
}  

以下是一些优质链接供您参考:

https://learn.microsoft.com/en-us/training/modules/msgraph-access-file-data/?WT.mc_id=M365-MVP-9698

https://medium.com/how-tos/how-to-upload-files-to-onedrive-or-sharepoint-using-microsoft-graph-api-and-csom-1d052b21e0a8

© www.soinside.com 2019 - 2024. All rights reserved.