我正在尝试使用Microsoft Graph(测试版)将文档上传到Microsoft Teams,但文档在成功上传后会损坏。
使用Graph,我首先创建一个Group,创建一个基于Group的Team,添加一些Team Members,最后将文档上传到默认通道。
除了上传的文档损坏且Office Online编辑器无法打开它之外,一切正常。但是,我们可以下载文件并在更正文件后在Microsoft Word中打开。
以下是我用于文档上传的代码 - >
FileInfo fileInfo =
new FileInfo(@"F:\Projects\TestProjects\MSTeamsSample\MSTeamsSample\Files\Test File.docx");
var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
var endpoint = $"https://graph.microsoft.com/beta/groups/{groupId}/drive/items/root:/General/{fileInfo.Name}:/content";
var fileContent = new ByteArrayContent(bytes);
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("application/octet-stream");
var requestContent = new MultipartFormDataContent();
requestContent.Add(fileContent, "File", fileInfo.Name);
var request = new HttpRequestMessage(HttpMethod.Put, endpoint);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", "<Access Token>");
request.Content = requestContent;
var client = new HttpClient();
var response = client.SendAsync(request).Result;
我尝试将内容类型更改为application/vnd.openxmlformats-officedocument.wordprocessingml.document
,但没有运气。我不明白这里有什么不妥。基于此documentation,代码非常简单。任何帮助将受到高度赞赏。
答案 0 :(得分:1)
请试试这个:
var filePath = @"F:\Projects\TestProjects\MSTeamsSample\MSTeamsSample\Files\Test File.docx";
var fileName = Path.GetFileName(filePath);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var endpoint = $"https://graph.microsoft.com/beta/groups/{groupId}/drive/items/root:/General/{fileName}:/content";
using (var client = new HttpClient())
{
using (var content = new StreamContent(fileStream))
{
content.Headers.Add("Content-Type", MimeMapping.GetMimeMapping(fileName));
// Construct the PUT message towards the webservice
using (var request = new HttpRequestMessage(HttpMethod.Put, endpoint))
{
request.Content = content;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.Token);
// Request the response from the webservice
using (var response = await client.SendAsync(request))
{
// Check the response.
}
}
}
}
我可以在Microsoft Teams编辑器中看到Word文档。