2

我正在尝试从我的 PHP 应用程序将文件发布到第 3 方 API。这可以从命令行工作:

curl -F "file=@move_file.MOV" "https://upload.wistia.com?project_id=pbmcmua3ot&username=api&api_password=xxxxx_apikey_yyyyy"

但我无法使用 PHP 的 curl 让它工作:

    $data = array(
        'username'      => $username,
        'api_password'  => $api_password,
        'file'          => fopen($tmp_filename, 'r'),
        'project_id'    => $project_hashed_id,
        );


    $ch = curl_init();
    //curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, "https://upload.wistia.com" );
    curl_setopt($ch, CURLOPT_UPLOAD, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout

    curl_setopt($ch, CURLOPT_INFILE, fopen($tmp_filename, 'r') );
    curl_setopt($ch, CURLOPT_NOPROGRESS, false);
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tmp_filename));

    curl_setopt($ch, CURLOPT_VERBOSE, 1); //for debugging
    curl_setopt($ch, CURLOPT_HEADER, true);

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result);

我认为CURLOPT_INFILE是问题,但我不确定。提前感谢您能给我的任何帮助。

更新1

    $data = array(
        'username'      => $username,
        'api_password'  => $api_password,
        'file'          => '@'.$tmp_filename,
        'project_id'    => $project_hashed_id,
        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, "https://upload.wistia.com" );
    curl_setopt($ch, CURLOPT_UPLOAD, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
    curl_setopt($ch, CURLOPT_NOPROGRESS, false);
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tmp_filename));
    curl_setopt($ch, CURLOPT_VERBOSE, 1); //for debugging
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result);

更新 2(工作)

    $data = array(
        'api_password'  => $api_password,
        'file'          => '@'.$tmp_filename,
        'project_id'    => $project_id
        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, "https://upload.wistia.com" );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
    $result = curl_exec($ch);
    curl_close($ch);
4

1 回答 1

2

你不需要为 curl 打开一个句柄,只需

$data = array(
    'file' => '@move_file.MOV'
);

Curl 将看到@并将其视为文件上传尝试。你也不必这样做http_build_query()。Curl 可以直接接受一个数组并自行构建查询:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
于 2013-07-25T18:24:02.637 回答