【问题标题】:Uploading file to onedrive using microsoft graph api使用 microsoft graph api 将文件上传到 onedrive
【发布时间】:2020-05-29 01:18:50
【问题描述】:

我正在尝试使用 microsoft graph api 和 laravel 中的 php sdk 实现将视频文件上传到 onedrive。

代码详情如下

// Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = json_encode([ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ]);
    //dd(json_encode($postData));

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }

也不确定项目路径中应该包含什么,我尝试使用文件夹名称但出现错误,我还尝试排除项目路径但仍然出现错误。

这是我遇到的错误

Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
 "error": {
 "code": "BadRequest",
 "message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)

请求数据的Json Encode也如下,我无法弄清楚问题...

{"items":
  {
    "@odata.type":"microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior":"rename",
    "name":"new_video.mp4"
 }
}

【问题讨论】:

  • 将内容类型标头设置为 application/json
  • @EliasSoares,是的,我添加了,但仍然遇到同样的错误

标签: laravel microsoft-graph-api onedrive microsoft-graph-files


【解决方案1】:

根据msgraph-sdk-php 存储库中给出的this example,您不需要json_econde 您的身体数据。 sdk 会为您完成。

所以你的代码应该是这样的:

    // Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = [ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ];

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多