问题描述
问题,我正在尝试创建一个新的docx文件,其中包含一些文本,但无法传递数据,因为没有示例如何在MS Graph API中上传实际文件
不知道内容和二进制流中要附加到正文中的变量是什么。如果我注释了attachBody()
参数,它将仅通过在文档文件夹的根目录中创建一个文本文件来起作用。
$graph = new Graph();
$graph->setAccesstoken($accesstoken);
$content = [
'Content-Type: text/plain
The contents of the file goes here.'
];
$data = $graph->createRequest('PUT','/sites/09e0add7-675f-4694-a1d9-999be420a807/drives/b!163gCV9nlEah2Zmb5CCoBwohbFPtU9lDr3_IcXUI8qiDyOuVQMhDSohSZRBTS6YL/root:/test.docx:/content')
->attachBody($content)
->setReturnType(Model\User::class)
->execute();
问题已更新 将文本/文档/图像/数据转换为二进制流,然后执行请求
下面执行前打印查询
$text_data=file_get_contents('C:\Users\Lab1-WS-5\Downloads/demo.docx');
$encoded_text_data=base64_encode($text_data);
// ------------------------------------------------------------------------
$graph = new Graph();
$graph->setAccesstoken($accesstoken);
// $content = 'The contents of the file goes here.';
// $encoded = base64_encode($content);
$data = $graph->createRequest('PUT','/sites/09e0add7-675f-4694-a1d9-999be420a807/drives/b!163gCV9nlEah2Zmb5CCoBwohbFPtU9lDr3_IcXUI8qiDyOuVQMhDSohSZRBTS6YL/root:/charlie.docx:/content')
->addHeaders(array('Content-Type' => 'text/plain'))
->attachBody($encoded_text_data)
->setReturnType(Model\User::class)
->execute();
当前问题,使用graph api创建的文档无法打开,而没有手动上传的文件。
解决方法
PS 无需使用base 64编码,因为Microsoft在线单词将无法阅读
工作代码
$text_data=file_get_contents('C:\Users\Lab1-WS-5\Downloads/wordfile.docx');
$graph = new Graph();
$graph->setAccessToken($accessToken);
$data = $graph->createRequest('PUT','/sites/09e0add7-675f-4694-a1d9-999be420a807/drives/b!163gCV9nlEah2Zmb5CCoBwohbFPtU9lDr3_IcXUI8qiDyOuVQMhDSohSZRBTS6YL/root:/wordfile1.docx:/content')
->addHeaders(array('Content-Type' => 'text/plain'))
->attachBody($text_data)
->setReturnType(Model\User::class)
->execute();
PS 这段代码可以与我测试过的excel和word的任何文件一起使用