【问题标题】:Invalid file type returned when posting via PHP Curl通过 PHP Curl 发布时返回的文件类型无效
【发布时间】:2016-06-16 03:52:23
【问题描述】:

我正在使用 CURL 将图像发布到 API。它完美地工作。但是当我对 php 做同样的事情时,会出现一些无法解决的问题。我尝试在 php.ini 文件中将CURLOPT_SAFE_UPLOAD 设置为TRUE

API 可以接受访问令牌作为 URL 参数和标头。

curl -v -F 'image=@/var/www/devel/id-card-concept.jpg;type=image/jpeg' -F 'title=test upload' -F 'description=test upload description' -H "Authorization: Bearer Access-Token" "https://api.site.com/v1/uploads"

以下是我的 PHP 代码:

$filename = 'id-card-concept.jpg';
$target_url = "https://api.site.com/v1/uploads?access_token=Access-Token";
$file_name_with_full_path = realpath('id-card-concept.jpg');
$post = array('title' => 'Via Api','image'=>'@'.$filename);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

我收到以下错误:

Array ( ) { "message": "Validation failed.", "errors": [ { "attribute": "image", "message": "is an invalid file type" } ] }

据我了解,该图像未通过验证。

【问题讨论】:

  • 你的数据包嗅探器显示什么?

标签: php image post curl


【解决方案1】:

尝试更改:

$post = array('title' => 'Via Api','image'=>'@'.$filename);

收件人:

$post = array('title' => 'Via Api','image'=>'@/var/www/devel/'.$filename.';type=image/jpeg');

或至:

$post = array('title' => 'Via Api','image'=>'@'.$file_name_with_full_path.$filename.';type=image/jpeg');

查看完整的正确代码:

$filename = 'id-card-concept.jpg';
$post = array('title' => 'Via Api','file'=>'@/var/www/devel/'.$filename.';type=image/jpeg');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.site.com/v1/uploads?access_token=cfbf79449f6b71212b3983a49be0056dcb6cd0838c6904bdb9a8f461f9e04220");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

function.curl-setopt上查看更多信息。

【讨论】:

  • 谢谢,代码不工作。现在由于某种原因,它显示了一个完全主题的 404 页面。还没发帖。
  • 404 文件未找到?检查访问浏览器的页面地址。代码是正确的。
  • 你是对的,网址中有错字。但是,我仍然收到错误消息。 { "message": "Validation failed.", "errors": [ { "attribute": "image", "message": "is an invalid file type" } ] 。可能与文件格式有关吗?在我问题的上述 curl 示例中,我将 ;type=image/jpeg 与图像文件名一起传递。
  • $post = array('title' => 'Via Api','image'=>'@'.$filename.';type=image/jpeg'); 这行得通。 :) 非常感谢。我将答案标记为正确。请更新特定行。你拯救了我的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 2017-11-21
  • 2015-05-09
  • 1970-01-01
相关资源
最近更新 更多