【问题标题】:How to send “multipart/related” content type in PHP如何在 PHP 中发送“多部分/相关”内容类型
【发布时间】:2017-04-21 08:23:30
【问题描述】:

我需要使用 PHP 发送多部分/相关内容。 内容将存在 3 个文件(2x XML,1xPDF) XML 文件需要编码为 7bit PDF 文件需要编码为 base64

我可以像这样构建一个文件,但是我不知道如何在 PHP 中使用 curl 发送它。

内容应该是这样的(我去掉了大部分编码的pdf)。这个例子来自另一个闭源应用程序:

MIME-Version: 1.0
Content-Type: multipart/related; 
    boundary="----=_Part_0_869724450.1481019442425"

------=_Part_0_869724450.1481019442425
Content-Type: application/vnd.cip4-jmf+xml; name=SubmitQueueEntry.jmf
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=SubmitQueueEntry.jmf
Content-ID: <5cba3621:158d3a34526:-7ffe@hp.com>
Content-Length: 465

<?xml version="1.0" encoding="UTF-8"?>
<JMF xmlns="http://www.CIP4.org/JDFSchema_1_1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" SenderID="Alces 0.9.9.1" TimeStamp="2012-08-21T14:55:08-06:00" Version="1.3">
  <Command ID="ALCES_YECIYJ_4_20120821145508" Type="SubmitQueueEntry" xsi:type="CommandSubmitQueueEntry">
    <QueueSubmissionParams ReturnJMF="http://YOURHOSTNAME:9090/jmf" URL="cid:5cba3621:158d3a34526:-7fff@hp.com" />
  </Command>
</JMF>

------=_Part_0_869724450.1481019442425
Content-Type: application/vnd.cip4-jdf+xml; name=test.pdf.jdf
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=test.pdf.jdf
Content-ID: <5cba3621:158d3a34526:-7fff@hp.com>
Content-Length: 1536

<?xml version="1.0" encoding="UTF-8"?>
<JDF xmlns="http://www.CIP4.org/JDFSchema_1_1" Type="Combined" ID="rootNodeId" Status="Waiting" JobPartID="My Job Part ID" Version="1.3" Types="DigitalPrinting" DescriptiveName="My Job" JobID="My Job ID">
   <Comment Name="JobSpec">Photobook</Comment><ResourcePool>
      <Media Class="Consumable" ID="M001" Status="Available" />
      <DigitalPrintingParams Class="Parameter" ID="DPP001" Status="Available" />
      <RunList ID="RunList_1" Status="Available" Class="Parameter">
            <LayoutElement>
               <FileSpec MimeType="application/pdf" URL="cid:5cba3621:158d3a34526:-8000@hp.com" />
            </LayoutElement>
      </RunList>
      <Component ID="Component" ComponentType="FinalProduct" Status="Unavailable" Class="Quantity" />
   <NodeInfo ID="NI001" Class="Parameter" Status="Available" LastEnd="2015-01-21T13:14:40" JobPriority="50"><Comment Name="Instructions">Emboss with gold stitch</Comment><GeneralID IDUsage="EmbossText" IDValue="Sara and Michael's Wedding,EmbossFontSize 20pt" /></NodeInfo><CustomerInfo Class="Parameter" ID="CI001" Status="Available" /></ResourcePool>
   <ResourceLinkPool>
      <MediaLink rRef="M001" Usage="Input" />
      <DigitalPrintingParamsLink rRef="DPP001" Usage="Input" />
      <RunListLink rRef="RunList_1" Usage="Input" />
      <ComponentLink Usage="Output" rRef="Component" Amount="1" />
   <NodeInfoLink rRef="NI001" Usage="Input" /><CustomerInfoLink rRef="CI001" Usage="Input" /></ResourceLinkPool>
</JDF>

------=_Part_0_869724450.1481019442425
Content-Type: application/octet-stream; name=_113HN_test.pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=_113HN_test.pdf
Content-ID: <5cba3621:158d3a34526:-8000@hp.com>
Content-Length: 576230

JVBERi0xLjUNJeLjz9MNCjEgMCBvYmoNPDwvTWV0YWRhdGEgMiAwIFIvT0NQcm9wZXJ0aWVzPDwv
RDw8L09OWzUgMCBSXS9PcmRlciA2IDAgUi9SQkdyb3Vwc1tdPj4vT0NHc1s1IDAgUl0+Pi9QYWdl
cyAzIDAgUi9UeXBlL0NhdGFsb2c+Pg1lbmRvYmoNMiAwIG9iag08PC9MZW5ndGggMjcwNDIvU3Vi
dHlwZS9YTUwvVHlwZS9NZXRhZGF0YT4+c3RyZWFtDQo8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9
...
bg0KMDAwMDM2NjI5NSAwMDAwMCBuDQowMDAwMzk1NDY2IDAwMDAwIG4NCjAwMDA0MTk5MjggMDAw
MDAgbg0KdHJhaWxlcg08PC9TaXplIDQxL1Jvb3QgMSAwIFIvSW5mbyA0MCAwIFIvSURbPEM3MjlE
QzVEMUYwODQzNDA4NEY0QTlBNEJBQTE4RjhCPjxDMjU2RDIxQjA5Q0Y0MjQ4QTA5REIzRDgxNjQw
NkMzMT5dPj4Nc3RhcnR4cmVmDTQyMDEyMQ0lJUVPRg0=
------=_Part_0_869724450.1481019442425--

我尝试了以下方法,但结果为空:

  $url="1.2.3.4";
  $data = array('name' => basename($filePath), 'file' => '@' . realpath($filePath));
  $data = array('file' => '@' . realpath($filePath));

  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-type: multipart/related'
    )); 
  $result = curl_exec($ch);

  $info = curl_getinfo($ch);
//  curl_close($ch);

  if ($result === false || $info['http_code'] != 200) {
    $output = "No cURL data returned for $url [" . $info['http_code'] . "]";
    if (curl_error($ch))
      $output .= "\n" . curl_error($ch);
  }
  else {
    // 'OK' status; format $output data if necessary here:
    echo 'succes';
  }

也许使用 curl-options 构建完整内容是一种更好的方法?而不是之前“手动”构建内容......

提前致谢!

【问题讨论】:

  • 你所说的空结果究竟是什么意思?您有一个 if/else 语句,您期望非空输出。您收到errorsuccess 消息吗?如果是error 消息,返回什么http_code
  • 参见stackoverflow.com/questions/25986167/…,tl;dr 是 curl 没有内置功能来使用 multipart/related 对请求进行编码,您必须自己手动对其进行编码
  • 另外既然你要处理curl和发送文件,还要检查CURLFile类php.net/manual/en/class.curlfile.php#class.curlfile也检查这里的第一个例子php.net/manual/en/curlfile.construct.php
  • 最后但同样重要的是检查这个例子http://php.net/manual/en/curlfile.construct.php#115160 我认为它涵盖了主题

标签: php curl mime multipart


【解决方案1】:

根据https://stackoverflow.com/a/25998544/1067003,libcurl 没有内置机制将请求编码为多部分/相关(这个人是 curl 的作者和主要开发人员,所以他知道),这意味着您必须自己编码主体.

我无权访问要测试的服务器,但我认为它会是这样的:

<?php
declare(strict_types = 1);
$files = array (
        new MultipartRelatedFile ( 'foo.php' ),
        new MultipartRelatedFile ( 'bar.php' ),
        new MultipartRelatedFile ( 'baz.php' ) 
);
$body = generateMultipartRelatedBody ( $files, $boundary );
$ch = curl_init ();
curl_setopt_array ( $ch, array (
        CURLOPT_HTTPHEADER => array (
                'Content-Type: multipart/related; boundary="' . $boundary.'"' 
        ),
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_URL => 'http://127.0.0.1:9999' 
) );
curl_exec ( $ch );
class MultipartRelatedFile {
    public $path;
    public $postname;
    public $content_type;
    function __construct(string $path) {
        if (! is_readable ( $path )) {
            throw new \Exception ( 'file is not readable!' );
        }
        $this->path = $path;
        $this->content_type = mime_content_type ( $path );
        $this->postname = basename ( $path );
    }
}
/**
 * generate http body for a multipart/related POST request
 *
 * @param MultipartRelatedFile[] $files
 * @param string|null $boundary
 */
function generateMultipartRelatedBody(array $files, string &$boundary = NULL): string {
    if (null === $boundary) {
        $boundary = bin2hex ( random_bytes ( 10 ) );
    }
    $n = "\r\n";
    $body = '';
    foreach ( $files as $file ) {
        $body .= $boundary . $n;
        $body .= 'Content-Disposition: attachment; filename=' . $file->postname . $n;
        $body .= "Content-Type: " . $file->content_type . $n;
        $body .= $n . file_get_contents ( $file->path ) . $n;
    }
    $body .= $boundary . '--';
    return $body;
}

警告:无法确保它在 netcat 服务器中看起来是正确的,这是未经测试的代码。 我还想指出,规范没有提到任何 Content-Length 标头,并暗示如果以其他方式提供文件名(如 Content-Disposition)和 start,则 Content-Id 是可选的不使用标头。 无论如何,可以在这里找到规格:https://www.rfc-editor.org/rfc/rfc2112

编辑:忘记在初始 Content-Type 标头的边界周围添加引号 ("),已修复。

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2017-07-06
    • 2013-03-22
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多