如何使用php cURL将图像上传到iNaturalist?

时间:2018-12-14 08:42:59

标签: php curl

一直在使用php cURL使用iNaturalist POST / observation_photos api将观测照片发布到iNaturalist,但我无法这样做。经过研究后,在github上发现了this,我尝试了代码,但收到错误“状态”:422。

我的代码:

<?php
require './init.php';

if ( isset($_POST['submitfile']) )
{
    // Make sure there are no upload errors
    if ($_FILES['upfile']['error'] > 0)
    {
        die("Error uploading file...");
    }
    $token = $_SESSION['access_token'];
    $file_path = 'c:\Users\hp\Pictures\New folder';

    $suffix = 'image/jpeg';

    $photo_name = $_FILES['upfile']['name'];

    $inat_id = 'White Magnolia';

    $boundary = rand(10,100);
    $body = '';
    $body .= '--' . $boundary . "\r\n";
    $body .= 'Content-Disposition: form-data; name="upfile"; filename=' . basename($file_path) . "\"\r\n";
    $body .= 'Content-Type: ' . $suffix . "\r\n\r\n";
    $body .=file_get_contents($photo_name) . "\r\n";
    $body .= '--' . $boundary . "\r\n";
    $body .= 'Content-Disposition: form-data; name="observation_photo[observation_id]"' . "\r\n";
    $body .= 'Content-Type: application/json' . "\r\n\r\n";
    $body .= json_encode(['observation_id' => $inat_id]) . "\r\n";
    $body .= '--' . $boundary . '--' . "\r\n";

    $photo_payload = array('observation_photos'=>array(
        'method'=>'POST',
        'timeout'=>'10',
        'headers'=> array(
            'Authorization'=>'Bearer'.$token,
            'Content-Type'=>'multipart/form-data;'
        ),
        'body' => $body
    ));
    $payload = json_encode($photo_payload);

    print_r($payload);

    echo "<hr><br>";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.inaturalist.org/v1/observation_photos?access_token=".$token);
    //curl_setopt($ch, CURLOPT_URL, "https://api.inaturalist.org/v1/observations?access_token=".$token);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    $result = curl_exec($ch);
    curl_close($ch);

    // Print the result?
    print_r($result);
}
?>
 <hr>
 <br>
<form action="" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="upfile">
    <input type="submit" value="Upload File" name="submitfile">
</form>

上传图片时出现错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

我发现了1或2个问题。

  1. $file_path = realpath('white magnolia.jpg');这不应该是文件路径(位置)而不是实际的文件名吗?
  2. 您的$photo_name('white magnolia.jpg')是否需要下划线而不是空格? $photo_name('white_magnolia.jpg')

我几乎可以肯定上面的第1项是您的主要问题,但我想指出,为防万一,您可能需要使用下划线。