$ch = curl_init ();
$fields = $params;
$fields ['file'] = '@' . $file;
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec ( $ch );
在php5.6之前的版本上以上面的代码上传文件是没有问题的,但从php5.6.0开始,需要加上curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false);这行代码方可上传,否则取不到文件。
最终的代码:
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false);
$fields = $params;
$fields ['file'] = '@' . $file;
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec ( $ch );注意:curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false);这行代码必须放在下面这行代码之前<pre name="code" class="plain">curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );否则上传到七牛时会报file is not specified in multipart的错误。
php官网上也有此介绍http://cn2.php.net/manual/en/function.curl-setopt.php
本文介绍了在PHP5.6及以上版本中上传文件时遇到的问题,即在不启用CURLOPT_SAFE_UPLOAD选项时,可能会导致'fileisnotspecifiedinmultipart'错误。文章详细解释了为何需要在设置文件参数之前启用该选项,并通过示例代码演示了解决方案。

被折叠的 条评论
为什么被折叠?



