CURL: Send images with boundary to REST API

后端 未结 2 1454
南笙
南笙 2021-01-21 07:04

Im currently working with some kind of API. I have wrote simple functions which allows me to add new content, however Im stuck on uploading images.

Here\'s simple CURL c

相关标签:
2条回答
  • 2021-01-21 07:45

    After several approaches using curl_file_create without getting it to work. I think the mobile.de-API is just implemented badly.

    I ended up implementing a custom routine for CURLOPT_POSTFIELDS that is creating the complete multipart manually. I borrowed most of the code from the PHP manpage as "The CURLFile class".

    1. Create an array of the filenames
    2. Create multipart header (see code below)

      function curl_custom_postfields(array $files = array())    {
      
      // build file parameters
      foreach ($files as $k => $v) {
          switch (true) {
              case false === $v = realpath(filter_var($v)):
              case !is_file($v):
              case !is_readable($v):
                  continue; // or return false, throw new InvalidArgumentException
          }
          $data = file_get_contents($v);
          $body[] = implode("\r\n", array(
              "Content-Disposition: form-data; name=\"image\"",
              "Content-Type: image/jpeg",
              "",
              $data,
          ));
      }
      
      // generate safe boundary
      do {
          $boundary = "---------------------" . md5(mt_rand() . microtime());
      } while (preg_grep("/{$boundary}/", $body));
      
      // add boundary for each parameters
      array_walk($body, function (&$part) use ($boundary) {
          $part = "--{$boundary}\r\n{$part}";
      });
      
      // add final boundary
      $body[] = "--{$boundary}--";
      $body[] = "";
      
      // set options
      return array(implode("\r\n", $body), $boundary);    
      }
      
    3. Use that function ;)

      $postfields = $this->curl_custom_postfields($files);
      
    4. Add boundary to http header

      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; boundary=' . $postfields[1], 'Accept: application/vnd.de.mobile.api+json'));
      
    5. Add Postfields

      curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields[0]);
      

    It's not the cleanest solution at all so please use it with care. But at least it works.

    0 讨论(0)
  • 2021-01-21 07:51

    I have the same problem and found a solution but only for single images. The trick is that your array MUST look like these:

    $images = array(
      'image' => 'PATH/IMG.jpg',
    );
    

    That means that the the key must be "image" and nothing other! I hope that helps ;)

    0 讨论(0)
提交回复
热议问题