Jad*_*nko 1 php upload onedrive microsoft-graph-api
我目前正在使用microsoft-php-sdk,它非常好。我已成功将小文件从服务器上传到 OneDrive。但当我尝试上传 38MB 的 Powerpoint 文件时却失败了。Microsoft Graph API 文档建议创建上传会话。我以为这就像将 URI 从/content更新到 / createUploadSession一样简单,但它仍然失败。
$response = $graph->createRequest('POST', '/me/drive/root/children/'.basename($path).'/createUploadSession')
->setReturnType(Model\DriveItem::class)
->upload($path);
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像这样。我很难弄清楚 PHP SDK 文档,并且没有上传会话的示例。有人用过 PHP SDK 来实现这个场景吗?
我对https://github.com/microsoftgraph/msgraph-sdk-php/wiki和 laravel 框架使用了类似的方法。这是最终对我有用的代码。
public function test()
{
//initialization
$viewData = $this->loadViewData();
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//upload larger files
// 1. create upload session
$fileLocation = 'S:\ebooks\myLargeEbook.pdf';
$file = \File::get($fileLocation);
$reqBody=array(
"@microsoft.graph.conflictBehavior"=> "rename | fail | replace",
"description"=> "description",
"fileSystemInfo"=> ["@odata.type"=> "microsoft.graph.fileSystemInfo"] ,
"name"=> "ebook.pdf",
);
$uploadsession=$graph->createRequest("POST", "/drive/root:/test/ebook.pdf:/createUploadSession")
->attachBody($reqBody)
->setReturnType(Model\UploadSession::class)
->execute();
//2. upload bytes
$fragSize =320 * 1024;// 1024 * 1024 * 4;
$fileLocation = 'S:\ebooks\myLargeEbook.pdf';
// check if exists file if not make one
if (\File::exists($fileLocation)) {
$graph_url = $uploadsession->getUploadUrl();
$fileSize = filesize($fileLocation);
$numFragments = ceil($fileSize / $fragSize);
$bytesRemaining = $fileSize;
$i = 0;
while ($i < $numFragments) {
$chunkSize = $numBytes = $fragSize;
$start = $i * $fragSize;
$end = $i * $fragSize + $chunkSize - 1;
$offset = $i * $fragSize;
if ($bytesRemaining < $chunkSize) {
$chunkSize = $numBytes = $bytesRemaining;
$end = $fileSize - 1;
}
if ($stream = fopen($fileLocation, 'r')) {
// get contents using offset
$data = stream_get_contents($stream, $chunkSize, $offset);
fclose($stream);
}
$content_range = "bytes " . $start . "-" . $end . "/" . $fileSize;
$headers = array(
"Content-Length"=> $numBytes,
"Content-Range"=> $content_range
);
$uploadByte = $graph->createRequest("PUT", $graph_url)
->addHeaders($headers)
->attachBody($data)
->setReturnType(Model\UploadSession::class)
->setTimeout("1000")
->execute();
$bytesRemaining = $bytesRemaining - $chunkSize;
$i++;
}
}
dd($uploadByte);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3683 次 |
| 最近记录: |