You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用最新Graph API和Java复制指定位置SharePoint文件的问题

解决Graph API新版本无root()方法时的SharePoint文件上传问题

在Graph SDK v5后续版本中,原root()方法被移除,需改用items("root")访问站点驱动器根目录,以下是适配你的业务逻辑的完整实现方案:

核心代码实现

先处理目标路径的构造(添加日期前缀、文件名加时间戳),再调用新版API完成上传:

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// 配置参数
String siteId = "你的站点ID";
String sourceFilePath = "Folder1/Folder2/file.txt"; // 来自其他系统的源路径
String localFilePath = "本地文件路径"; // 待上传的本地文件路径

// 1. 构造目标路径
// 生成YYYYMMDD格式的日期文件夹
String dateFolder = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
// 生成文件名用的时间戳
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

// 拆分源路径的文件夹部分与原始文件名
int lastSlashIndex = sourceFilePath.lastIndexOf('/');
String sourceFolderPart = lastSlashIndex != -1 ? sourceFilePath.substring(0, lastSlashIndex) : "";
String originalFileName = lastSlashIndex != -1 ? sourceFilePath.substring(lastSlashIndex + 1) : sourceFilePath;

// 给文件名追加时间戳
int lastDotIndex = originalFileName.lastIndexOf('.');
String fileNameWithoutExt = lastDotIndex != -1 ? originalFileName.substring(0, lastDotIndex) : originalFileName;
String fileExt = lastDotIndex != -1 ? originalFileName.substring(lastDotIndex) : "";
String newFileName = fileNameWithoutExt + "_" + timestamp + fileExt;

// 拼接最终目标路径
String destinationPath;
if (sourceFolderPart.isEmpty()) {
    destinationPath = String.format("%s/%s", dateFolder, newFileName);
} else {
    destinationPath = String.format("%s/%s/%s", dateFolder, sourceFolderPart, newFileName);
}

// 2. 读取本地文件字节
byte[] fileBytes;
try (FileInputStream fileStream = new FileInputStream(localFilePath)) {
    fileBytes = fileStream.readAllBytes();
} catch (IOException e) {
    throw new RuntimeException("读取文件失败", e);
}

// 3. 调用新版Graph API上传文件
graphServiceClient.sites(siteId)
        .drive()
        .items("root") // 替代旧版的root()方法
        .itemWithPath(destinationPath)
        .content()
        .put(fileBytes);

关键说明

  • 无需驱动器ID:sites(siteId).drive()依然自动指向站点默认文档库驱动器,无需手动指定驱动器ID,保持原逻辑不变。
  • 路径构造逻辑:严格保留源路径的文件夹结构,在开头添加YYYYMMDD格式的日期文件夹,同时给文件名追加时间戳避免文件冲突。
  • API适配:用items("root")完全替代旧版的root()方法,上传调用逻辑与旧版一致,仅调整根目录访问方式。

内容的提问来源于stack exchange,提问作者Megan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:47:04