0
votes

I am using IBM watson visual recognition api when I add an image to collection but I receive following error always:

string(59) "{ "error": "Missing multipart/form-data", "code": 400 }" bool(true)

here is my code:

 <?php
 if ( isset($_FILES['uploadedfile']) && $_POST!="" ) {
 $targetPath = 'uploads/'.basename($_FILES['uploadedfile']['name']);
 $url = 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/searchItems_c5c677/images?api_key=655e4118jgfd8e967ce58ee0b67behjfh3ebfad22e38a34e&version=2016-05-20';
 $fileData = $_FILES['uploadedfile']['name'];
 $post_data = array(
        'image_file' => $fileData
 );
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
 $headers = array();
 $headers[] = "Content-Type: multipart/form-data";
 $headers[] = "Accept: application/json";
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $result = curl_exec($ch);
 if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);die;
 }
   var_dump($result, true);die;
 }
?>
<form enctype="multipart/form-data" method='post' action="index.php">
  <input name="uploadedfile" type="file" value="choose">
  <input type="submit" value="Upload">
</form>
1

1 Answers

0
votes

I have review your code and make some changes and now its working.

if (isset($_FILES['uploadedfile']) && $_POST != "") {
    $targetPath = 'uploads/' . basename($_FILES['uploadedfile']['name']);
    $url = 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={your_key}&version=2016-05-20';
    $post_data = array(
        'file' =>
        '@' . $_FILES['uploadedfile']['tmp_name']
        . ';filename=' . $_FILES['uploadedfile']['name']
        . ';type=' . $_FILES['uploadedfile']['type']
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $headers = array();
    $headers[] = "Content-Type: multipart/form-data";
    $headers[] = "Accept: application/json";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
        die;
    }
    var_dump($result, true);
    die;
}