我正在使用下面的 Microsoft Graph API 代码将文件上传到 OneDrive 以供当前登录用户的业务使用。该代码可以很好地上传记事本 .txt 文件,我可以按原样正确打开文件。但是,当它上传 .docx(word 文档)时,在打开尝试时会因为文件损坏而引发错误。我在这里缺少什么?使用的参考 - https://blog.mastykarz.nl/2-practical-tips-office-365-group-files-api/ https://graph.microsoft.io/en-us/docs/api-reference/v1 .0/api/item_uploadcontent
代码:
byte[] filebytes= fileuploadControl.FileBytes;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Put, "https://graph.microsoft.com/v1.0/me/drive/root/children/" + filename + "/content"))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Headers.Add("Accept", "application/json;odata.metadata=verbose");
request.Content = new StringContent(DecodeFrom64(Convert.ToBase64String(filebytes)),System.Text.Encoding.ASCII, "text/plain");
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
lblFileUpload.Text = "File uploaded successfully";
}
}
}
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}