Microsoft Graph API文件上传到Onedrive中用于商业



我正在使用以下Microsoft Graph API代码将文件上载到OneDrive,用于当前登录用户的业务。该代码上传notepad.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;
    }

下面的代码非常适合我。代码

var fileUrl = new Uri("https://graph.microsoft.com/v1.0/me/drive/root/children/" + filename + "/content");
                    var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(fileUrl);
                    request.Method = "PUT";
                    request.ContentLength = filebytes.Length;
                    request.AllowWriteStreamBuffering = true;
                    //request.Accept = "application/json;odata=verbose";
                    request.ContentType = "text/plain";
                    request.Headers.Add("Authorization", "Bearer " + accessToken);
                    System.IO.Stream stream = request.GetRequestStream();
                    //filestream.CopyTo(stream);
                    stream.Write(filebytes, 0, filebytes.Length);
                    stream.Close();
                    System.Net.WebResponse response = request.GetResponse();

考虑到您在c#中,我认为您不需要首先对内容进行base64解码。您是否尝试删除解码部分并仅为请求对其进行编码?

相关内容

  • 没有找到相关文章

最新更新