I'm working on the Graph API client app 'Send Email'. In order to attach a file (> 3MB) to an email message, I would like to use uploadAsync() or upload() method in the LargeFileUploadTask class, instead of AttachmentFile#contentBytes(). AttachmentFile#contentBytes() method works fine except it is not memory-efficient. I would like to stream data in uploading the attachment files instead of using the byte array. The following code was tested with microsoft-graph Java SDK 5.64.0. It failed with "Error code: InvalidAudience Error message: The audience claim value is invalid ..." Also "401 : Unauthorized" can be seen in the stacktrace. It seems that microsoft-graph tried to upload the file content to https://outlook.office365.com URL while the access token works well for https://graph.microsoft.com URLs.
Long fileSize =7008981;
AttachmentItem attachItem = new AttachmentItem();
attachItem.attachmentType = AttachmentType.FILE;
attachItem.name = "yourAttachmentFilename.zip";
attachItem.size = fileSize;
UploadSession session = userRequestBuilder.messages(message.id).attachments()
.createUploadSession(AttachmentCreateUploadSessionParameterSet.newBuilder()
.withAttachmentItem(attachItem).build()).buildRequest().post();
InputStream stream = readFileInputStream(path); // get input stream from the attachment file
LargeFileUploadTask<FileAttachment> chunkUpload =
new LargeFileUploadTask<>(session, graphClient, stream,
fileSize, FileAttachment.class);
CompletableFuture<LargeFileUploadResult<FileAttachment>> task;
try {
task = chunkUpload.uploadAsync(chunkSize, null, callback);
largeFileUploadTasks.add(task); // add the task to a list of CompletableFuture objects
} catch (IOException e) {
// Error Handling
} finally {
IOUtils.closeQuietly(stream);
}
// After all the attachment file upload-tasks are submitted
try {
if (CollectionUtils.isNotEmpty(largeFileUploadTasks)) {
largeFileUploadTasks.forEach(CompletableFuture::join);
}
} catch (CompletionException e) {
// Error Handling
}
I tried all suggestions in the following links, but none was helpful:
https://github.com/microsoftgraph/msgraph-sdk-java-auth/issues/52#issuecomment-694415555
https://github.com/microsoftgraph/msgraph-sdk-java/issues/1380#issuecomment-1477372917