【问题标题】:PHP cURL creates empty file name only (0 bytes) - not transferring actual filePHP cURL 仅创建空文件名(0 字节) - 不传输实际文件
【发布时间】:2020-12-03 11:19:02
【问题描述】:

我正在使用文件类型输入通过 Ajax 将 FormData ($_FILES['files']) 传递给 PHP

我的 PHP cURL 如下所示:

$headers = array(
    "Authorization: Bearer " . <token>, 
    "Host: graph.microsoft.com",
    "Content-Type: multipart/form-data",
    "Content-Length: 0",
);

$filename = $_FILES['file']['name'];

$postfile = curl_init('https://graph.microsoft.com/v1.0/users/' . <userid> . '/drive/root:/<folder>/' . $filename . ':/content'); 
curl_setopt($postfile, CURLOPT_PUT, 1);
curl_setopt($postfile,CURLOPT_HEADER,false);
curl_setopt($postfile, CURLOPT_HTTPHEADER, $headers);
curl_setopt($postfile,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($postfile,CURLOPT_SSL_VERIFYHOST,0);

$result = curl_exec($postfile);
curl_close($postfile); 

这会在用户 OneDrive 的正确文件夹中创建一个具有正确扩展名和所有内容的文件,但它们都是空的(0 字节)。

我已经用许多不同类型的文件测试了几个小时,结果总是一样。

我哪里错了?

【问题讨论】:

  • 所以您尝试上传现有文件而不是创建新文件?
  • @AllenWu 是的,没错。我正在尝试将现有文件从我的计算机上传到 OneDrive。
  • 但我没有看到您从本地机器中获取文件的位置。调用 Microsoft Graph API 时,使用 file_get_contents 获取文件并传递它。见stackoverflow.com/questions/47262443/…stackoverflow.com/questions/47708226/…
  • 第二个答案是将大文件(> 4M)上传到O365。但是使用file_get_contents获取文件应该是一样的。
  • @AllenWu 不应该可以从 $_FILES['file']['tmp_name'] 获得吗?

标签: php curl azure-ad-graph-api form-data microsoft-graph-files


【解决方案1】:

您缺少文件数据 尝试将以下内容添加到您的 curl 中

$fh_res = fopen($_FILES['file']['tmp_name'], 'r');

curl_setopt($postfile, CURLOPT_INFILE, $fh_res);
curl_setopt($postfile, CURLOPT_INFILESIZE, filesize($_FILES['file']['tmp_name']));

【讨论】:

【解决方案2】:

我终于用以下方法解决了:

    $filename = $_FILES['file']['name'];
    $filecon = fopen($_FILES['file']['tmp_name'],'r');
    $filesize = filesize($_FILES['file']['tmp_name']);

    $headers = array(
        "Authorization: Bearer " . <token>, 
        "Host: graph.microsoft.com",
        "Content-Type: application/json",
        "Content-Length: " . $filesize,
    );

    $postfile = curl_init('https://graph.microsoft.com/v1.0/users/' . <userid> . '/drive/root:/<folder>/' . $filename . ':/content'); 
    
    curl_setopt($postfile, CURLOPT_PUT, 1);
    curl_setopt($postfile,CURLOPT_HEADER,0);
    curl_setopt($postfile, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($postfile, CURLOPT_UPLOAD, 1);
    curl_setopt($postfile, CURLOPT_INFILE, $filecon);
    curl_setopt($postfile, CURLOPT_INFILESIZE, $filesize);

    $result = curl_exec($postfile);
    curl_close($postfile); 

希望这有助于任何寻找 PHP cURL 上传到 OneDrive 的人!

【讨论】:

    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多