如何使用Graph SDK向SharePoint文档库上传文件新版本?
小文件(<4MB)直接上传
如果文件大小小于4MB,可直接通过PutAsync配合请求选项实现新版本上传,核心是指定**冲突行为为replace**并带上现有文件的ETag(确保操作针对目标文件):
// 1. 获取目标文件的现有信息,拿到ETag var existingFile = graphClient.Drives["{driveId}"].Root.ItemWithPath("{fileName}").GetAsync().Result; // 2. 配置请求选项:指定冲突行为和ETag var requestOptions = new List<Option> { new HeaderOption("If-Match", existingFile.ETag), new QueryOption("@microsoft.graph.conflictBehavior", "replace") }; // 3. 上传新版本文件流 using var fileStream = new FileStream("{filePath}", FileMode.Open); var updatedDriveItem = graphClient.Drives["{driveId}"].Root.ItemWithPath("{fileName}").Content .PutAsync(fileStream, requestOptions).Result;
大文件(≥4MB)分片上传
对于大文件,需要通过创建上传会话的方式实现分片上传,同样指定冲突行为为replace来生成新版本:
// 1. 创建上传会话,设置冲突行为为replace var uploadSession = graphClient.Drives["{driveId}"].Root.ItemWithPath("{fileName}") .CreateUploadSessionAsync(new DriveItemUploadableProperties { ODataType = null, ConflictBehavior = ConflictBehavior.Replace }).Result; // 2. 初始化大文件上传任务 using var fileStream = new FileStream("{filePath}", FileMode.Open); var maxChunkSize = 320 * 1024; // 可根据需求调整分片大小(建议320KB-4MB) var uploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, fileStream, maxChunkSize); // 3. 执行上传 var uploadResult = uploadTask.UploadAsync().Result; if (uploadResult.UploadSucceeded) { var updatedItem = uploadResult.ItemResponse; // 处理上传成功后的逻辑 }
为什么之前的方法失败?
Content.PatchAsync:该端点仅支持PUT/GET操作,不支持PATCH,直接替换请求方法无效。DriveItem.PatchAsync更新Content属性:DriveItem的Content是流式属性,无法通过常规的PATCH请求修改,必须通过专门的内容上传端点(即/content路径)处理。
内容的提问来源于stack exchange,提问作者Erik Almquist
相关产品推荐
相关产品推荐

