使用PHP cuRL上传文件

时间:2017-09-25 07:57:33

标签: php curl

我正在编写API,我想从表单POST上传。

这是我的html表单

<form method="post" action = 'function.php' enctype="multipart/form-data">
<input type = 'file' name = 'pictures' required>
<input type = 'submit'/>

这是我的function.php

$uploads_dir = 'img/BL/';
$tmp_name = $_FILES["pictures"]["tmp_name"];
$name = $_FILES["pictures"]["name"];
$asd =  move_uploaded_file($tmp_name, "$uploads_dir/$name");

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.example.com/upload/images.json",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $asd,
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic NDM0MDY1Mzc6TE9sSmV1V003aTg2a2x6Mw==",
    "cache-control: no-cache",
    "content-type: multipart/form-data",
    "postman-token: a88b550a-3544-85b7-ca6b-1ed8cc5cb35c"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
  // echo $name;
}

来自API的响应

{
status: "ERROR",
id: null,
message: "must have an image"
}

问题是图片已经保存,但是当我尝试使用cURL上传时,获取响应“Harus ada文件图片”(必须有图片)上传图像时没有读取/检测到

我是以错误的方式来做这件事的吗?任何建议都将非常感激。 也许有人可以告诉我线索,或者我的代码有什么问题,谢谢

0 个答案:

没有答案