如何使用MSGRAPH-SDK-PHP v2上传用户头像?
解决MS Graph PHP SDK用户头像上传问题
一、修复头像内容上传的类型错误
你遇到的Argument #1 ($body) must be of type Psr\Http\Message\StreamInterface, string given错误,是因为put方法要求传入PSR-7标准的Stream对象,而非字符串。只需把二进制字符串转换成StreamInterface实例即可,PHP SDK可借助GuzzleHttp\Psr7\Utils::streamFor()实现:
use GuzzleHttp\Psr7\Utils; $myPic = $appClient->users()->byUserId($userId)->photo()->content()->get()->wait(); if (null == $myPic) { return null; } $binary = $myPic->getContents(); // 将二进制字符串转为StreamInterface对象 $stream = Utils::streamFor($binary); $appClient->users()->byUserId($userId)->photo()->content()->put($stream)->wait();
二、使用setPhoto方法上传头像
setPhoto方法需要传入符合ProfilePhoto结构的数组,核心是提供@odata.type标识和图片的base64编码内容。示例代码如下:
// 读取本地图片并转为base64编码 $imagePath = '/path/to/your/image.jpg'; $imageContent = file_get_contents($imagePath); $base64Image = base64_encode($imageContent); $profilePhoto = [ '@odata.type' => '#microsoft.graph.profilePhoto', 'contentBytes' => $base64Image ]; $appClient->users()->byUserId($userId)->setPhoto($profilePhoto)->wait();
注意:确保应用已配置User.ReadWrite.All(应用权限)或User.ReadWrite(委派权限),且图片为JPEG/PNG格式、大小不超过4MB。
内容的提问来源于stack exchange,提问作者LittleBigFox
相关产品推荐
相关产品推荐

