You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:53:21