【发布时间】:2011-03-26 21:37:52
【问题描述】:
从服务器获取图像很简单,但我想到了一些不同的东西。这是一个疯狂的问题,但是......是否可以将文件(图像)发送到服务器但不使用表单上传或 ftp 连接?我想向例如发送请求。 http://www.example.com/file.php 带有二进制内容。我想我需要设置 Content-type header image/jpeg 但是如何在我的请求中添加一些内容?
【问题讨论】:
从服务器获取图像很简单,但我想到了一些不同的东西。这是一个疯狂的问题,但是......是否可以将文件(图像)发送到服务器但不使用表单上传或 ftp 连接?我想向例如发送请求。 http://www.example.com/file.php 带有二进制内容。我想我需要设置 Content-type header image/jpeg 但是如何在我的请求中添加一些内容?
【问题讨论】:
使用curl上传图片文件有多种方式,例如:
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/path/to/image.jpeg');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
//CURLOPT_SAFE_UPLOAD defaulted to true in 5.6.0
//So next line is required as of php >= 5.6.0
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
您可以在以下位置查看示例:http://au.php.net/manual/en/function.curl-setopt.php
【讨论】:
见http://docs.php.net/function.curl-setopt:
CURLOPT_POSTFIELDS 要在 HTTP“POST”操作中发布的完整数据。 要发布文件,请在文件名前加上 @ 并使用完整路径。这可以作为 urlencoded 字符串传递,如 'para1=val1¶2=val2&...' 或作为字段名称作为键和字段数据作为值的数组。如果 value 是一个数组,则 Content-Type 标头将设置为 multipart/form-data。
【讨论】:
PHP 7.0
唯一对我有用的代码$file = new \CURLFile('@/path/to/image.jpeg'); //<-- Path could be relative
$data = array('name' => 'Foo', 'file' => $file);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
//CURLOPT_SAFE_UPLOAD defaulted to true in 5.6.0
//So next line is required as of php >= 5.6.0
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
感谢@AndyLin 的回答和source。
【讨论】:
Andy Lin 使用的方法由于某种原因对我不起作用,所以我找到了这个方法:
function makeCurlFile($file){
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
$output = new CURLFile($file, $mime, $name);
return $output;
}
您可以通过将值与 $data 负载中的键相关联来发送其他内容,而不仅仅是文件,如下所示:
$ch = curl_init("https://api.example.com");
$mp3 =makeCurlFile($audio);
$photo = makeCurlFile($picture);
$data = array('mp3' => $mp3, 'picture' => $photo, 'name' => 'My latest single',
'description' => 'Check out my newest song');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
}
curl_close ($ch);
我认为这是因为出于安全原因,某些 API 不支持旧的执行方式。
【讨论】:
我使用这种从 HTML 表单发送照片的方法
$ch = curl_init();
$cfile = new CURLFile($_FILES['resume']['tmp_name'], $_FILES['resume']['type'], $_FILES['resume']['name']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $cfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
【讨论】:
VolkerK 完全正确,但我的经验表明发送文件“@”运算符仅适用于数组。
$post['file'] = "@FILE_Path"
现在您可以使用CURLOPT_POSTFIELDS发送文件
【讨论】: