无法使用 Java SDK 将文件上传到 OneDrive

Cannot Upload File to OneDrive with Java SDK

我无法使用 MS Graph Java SDK 将文件上传到 OneDrive,也找不到任何基于 Java 的示例。

我在这里发现了一个类似(但未回答)的问题:MS Graph Java SDK: how to upload a large file to OneDrive?

但是,我设法拼凑了上面提出的问题中显示的更多代码(基于基于 .NET 的示例),但仍然没有成功。

FileSystemInfo fileSystemInfo = new FileSystemInfo();
fileSystemInfo.createdDateTime = new GregorianCalendar();
fileSystemInfo.lastModifiedDateTime = new GregorianCalendar();

DriveItemUploadableProperties properties = new DriveItemUploadableProperties();
properties.name = "test.jpeg";
properties.description = "TEST_DESCRIPTION";
properties.fileSystemInfo = fileSystemInfo;

IDriveItemCreateUploadSessionRequest request = this.graphServiceClient
        .me()
        .drive()
        .root()
        .createUploadSession(properties)
        .buildRequest();

UploadSession session = request.post();

if(Objects.nonNull(session)) {
    int maxSizeChunk = (320 * 1024) * 4;
    String macOsPath = "[ADD YOUR VALID FILE PATH]";
    File file = new File(macOsPath);
    FileInputStream inputStream = new FileInputStream(file);

    ChunkedUploadProvider<File> uploadProvider = 
        new ChunkedUploadProvider(session, this.graphServiceClient, 
            inputStream, maxSizeChunk, File.class);

    IProgressCallback<File> callback = new IProgressCallback<File>() {        
        @Override
        public void progress(long l, long l1) {
            log.info("making progress: " + l + ", " + l1);
        }

        @Override
        public void success(File file) {
            log.info("Success! " + file.getName());
        }

        @Override
        public void failure(ClientException e) {
            log.info("Failure! " + e.getMessage());
        }
    };
    uploadProvider.upload(callback, 0);
}

尝试 post 上传会话请求时发生错误:

UploadSession session = request.post();

返回的不是上传会话,而是以下错误:

{
  "error": {
    "code": "invalidRequest",
    "message": "The request is malformed or incorrect.",
    "innerError": {
      "request-id": "b9d4026b-0d8f-44b4-9e9e-8d78a0ea5ea3",
      "date": "2019-05-30T16:20:11"
    }
  }
}

我不完全理解要求 DriveItemUploadableProperties 的原因,但您不应该设置它的任何属性。

试试改用这个:

UploadSession session = this.graphServiceClient
    .me()
    .drive()
    .root
    .itemWithPath("_hamilton.jpg")
    .createUploadSession(new DriveItemUploadableProperties())
    .buildRequest()
    .post();

我个人认为最有用的示例是 SDK 本身的单元测试。在这种情况下,您可以在 OneDriveTests.Java.

中找到它