使用 Curl 和 PHP 将分段 PUT 上传到 REST 端点


Multipart PUT upload using Curl and PHP to a REST endpoint

我需要将一个csv文件和一些使用多部分POST与PHP和Curl的POST字段HTTP放置到REST API端点。

文件上传的内容存储在变量$list中。另一个终点是$url。

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PUT, true);
$post = array(
    //Other Post fields array
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$fh = fopen('php://memory', 'rw');
fwrite($fh, $list);
rewind($fh);
curl_setopt($ch, CURLOPT_INFILE, $fh);  
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($list));  
$response = curl_exec($ch);

上面的代码似乎有效,唯一的问题是另一个端点需要文件上传的特定字段名称。如何设置文件名?

我做错了什么吗?

这是他们在API上提到的PUT格式

Content-Disposition: form-data; name="list[csv]"; filename="RackMultipart20110923-63966-hfpyg"
Content-Length: 33
Content-Type: text/csv
Content-Transfer-Encoding: binary
xxxx
yyyy
zzzz
-------------MultipartPost
Content-Disposition: form-data; name="list[list_type]"
Blacklist
-------------MultipartPost--

仅供参考,这是multipart/form-data.我认为您需要自己构建正文,我认为 cURL 无法使用 PUT 请求构建这种请求。但是,这不是一个严重的问题:

<?php
  function recursive_array_mpfd ($array, $separator, &$output, $prefix = '') {
    // Recurses through a multidimensional array and populates $output with a 
    // multipart/form-data string representing the data
    foreach ($array as $key => $val) {
      $name = ($prefix) ? $prefix."[".$key."]" : $key;
      if (is_array($val)) {
        recursive_array_mpfd($val, $separator, $output, $name);
      } else {
        $output .= "--$separator'r'n"
                 . "Content-Disposition: form-data; name='"$name'"'r'n"
                 . "'r'n"
                 . "$val'r'n";
      }
    }
  }
  // This will hold the request body string
  $requestBody = '';
  // We'll need a separator
  $separator = '-----'.md5(microtime()).'-----';
  // First add the postfields
  $post = array(
    //Other Post fields array
  );
  recursive_array_mpfd($post, $separator, $requestBody);
  // Now add the file
  $list = "this,is,some,csv,data"; // The content of the file
  $filename = "data.csv"; // The name of the file
  $requestBody .= "--$separator'r'n"
                . "Content-Disposition: form-data; name='"list[list_type]'"; filename='"$filename'"'r'n"
                . "Content-Length: ".strlen($list)."'r'n"
                . "Content-Type: text/csv'r'n"
                . "Content-Transfer-Encoding: binary'r'n"
                . "'r'n"
                . "$list'r'n";
  // Terminate the body
  $requestBody .= "--$separator--";
  // Let's go cURLing...
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_PUT, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: multipart/form-data; boundary="'.$separator.'"'
  ));
  $response = curl_exec($ch);

如果您对此有任何问题,请尝试在 cURL 请求之前echo $requestBody;,并确保它看起来像您期望的那样。