【问题标题】:Upload a given File and POST-Date with CURL使用 CURL 上传给定的文件和 POST-Date
【发布时间】:2021-05-08 22:35:18
【问题描述】:

也许有人可以帮助我?我不解决这个问题

我有一个来自formualar 的POST 数组和一个已经存在于服务器上的文件。 任务是通过 CURL PUT 将 POST 数据和文件发送到 URL。

我已经尝试解决这个问题几个小时/几天了

我已经设置了标题Content-type: application/octet-stream 和带有$ch->setOption(CURLOPT_POSTFIELDS, http_build_query($data) 的字段

POST 数据如下所示:

$data = array (
  'field1' => 'lorem',
  'field2' => 'ipsum',
  'field3' => 'dolor'
);

使用说明(php.net、stackoverflow 等)

https://kb.detlus.com/articles/php/upload-files-using-curl/

https://www.php.net/manual/de/curlfile.construct.php

Is it possible to use cURL to stream upload a file using POST?

我尝试发送文件

不工作

$data = array (
  'field1' => 'lorem',
  'field2' => 'ipsum',
  'field3' => 'dolor'
  'file' => '@'.realpath('/abs/path/file.xlsx');
);

都没有

$data = array (
  'field1' => 'lorem',
  'field2' => 'ipsum',
  'field3' => 'dolor'
);

$data['file'] = curl_file_create('/abs/path/file.xlsx'], mime_content_type('/abs/path/file.xlsx'), 'file.xlsx');

这导致以下数组

$data = array (
  'field1' => 'lorem',
  'field2' => 'ipsum',
  'field3' => 'dolor',
  'file' => 
  array (
    'file' => 
    CURLFile::__set_state(array(
       'name' => '/abs/path/file.xlsx',
       'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
       'postname' => '/abs/path/file.xlsx',
    )),
  )
);

根据我尝试的版本,我会收到 400 或 500 错误。

有没有人可以帮助我的提示? 我做错了什么?

【问题讨论】:

  • FWIW the manual 中的示例都显示 new CURLFile 调用或 curl_file_create 正在完成,结果是添加到帖子数据中的 file 数组中。从您最后一个数组的外观来看,$data 下的第二级文件可能会导致您的问题。

标签: php curl post upload


【解决方案1】:

我认为这里的主要问题是您使用了错误的内容类型。

对于文件上传,您应该使用“Content-Type: multipart/form-data”。 取自维基百科(在多部分子类型中)MIME

MIME 类型 multipart/form-data 用于表示通过表单提交的值。最初定义为 HTML 4.0 的一部分,它最常用于通过 HTTP 提交文件。它在 RFC 7578 中指定,取代 RFC 2388。

我写了这个sn-p,希望对你有帮助(对不起非OOP版本的代码,我没有安装PHP 8,我用的是PHP 7.4,但你可以“翻译”很容易:D):

<?php
//This is a dummy data array, will contain your form fields (Advice: never trust user input, always check the values given before submitting)
$data = [
    'field1' => 'value',
    'field2' => 'value2',
    'field3' => 123
];

//The path to the file you want to upload
$fileName = 'somefile.xlsx';
$filePath = './../files/'.$fileName;

//Security check
if (file_exists($filePath))
{
    //Adding the file to the $data array
    $data['file'] = curl_file_create($filePath, mime_content_type($filePath), $fileName);

    //Initialize the cURL handle
    $ch = curl_init('https://some-random-site.com/api/some/random/endpoint');

    //Set the request method (HTTP verb)
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

    //This will make curl "return" the response as string when we call curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //This SHALL NOT be used in production, unless you know the implications!!! But, if you have an HTTPS endpoint with a self-signed certificate you can skip checks
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //======

    //We set the data we want to send (curl will "transform" this for us
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    //Here the important part, setting the right content-type
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);

    //Execute the call and get the response as string
    $res = curl_exec($ch);
    if ($res === false)
    {
        //An error occurred, print out
        echo 'ERROR: '.curl_error($ch);
    }
    else
    {
        //Execution succeeded, do whatever with the response
        //Hint: this does not mean that the server answered with a success status but rather, it indicates that the curl execution has succeeded

        //If you want to check the HTTP status of the request you can get it like this:
        //$info = curl_getinfo($curl);
        //echo $info['http_code'];

        //Do whatever with the response (I'm just printing it).
        echo $res;
    }

    curl_close($ch);
}
else
{
    echo 'File not found.';
}

我真的希望这会有所帮助,不幸的是,我不知道您将请求提交到的 URL/API,因此我无法在您的端点上对其进行测试。我自己做了一个端点:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'PUT')
{
    $c = file_get_contents('php://input');
    die(var_dump($c));
}

我得到的输出显示了所有字段和文件上传。

--------------------------05a7619c906d94df Content-Disposition: form-data; name="field1" value

 --------------------------05a7619c906d94df Content-Disposition: form-data; name="field2" value2

 --------------------------05a7619c906d94df Content-Disposition: form-data; name="field3" 123

 --------------------------05a7619c906d94df Content-Disposition: form-data; name="file"; filename="./../conf/test.xlsx" Content-Type:
 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
 ........LOTS_OF_BYTES_OF_THE_XLSX_FILE_:P......
 --------------------------05a7619c906d94df--

【讨论】:

    【解决方案2】:

    感谢您的帮助!!! 解决方案 => Content-Type: multipart/form-data

    【讨论】:

      猜你喜欢
      • 2012-09-21
      • 2015-01-02
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2017-02-03
      相关资源
      最近更新 更多