簡體   English   中英

如何使用php cURL將圖像上傳到iNaturalist?

[英]How to upload an image to iNaturalist using php cURL?

一直在使用php cURL使用iNaturalist POST / observation_photos api將觀察照片發布到iNaturalist,但我無法這樣做。 做了一些研究並在github上發現了這一點 ,我嘗試了代碼,但收到錯誤“狀態”: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>

上傳圖片時出現的錯誤:

在此處輸入圖片說明

我發現了1或2個問題。

  1. $file_path = realpath('white magnolia.jpg'); 這不應該是文件路徑(位置)而不是實際文件名嗎?
  2. $photo_name('white magnolia.jpg')需要下划線而不是空格? $photo_name('white_magnolia.jpg')

我幾乎可以肯定上面的第1項是您的主要問題,但我想指出,您可能需要加下划線以防萬一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM