【发布时间】:2017-04-21 19:27:57
【问题描述】:
我想上传图片文件。目标是具有 oAuth2 autohization 的 REST api 端点。我设法上传了一些东西,但是当我在服务器上打开文件时它已损坏。大小与源文件不匹配。
这是我使用的代码:
<?php
$file = 'example.jpg';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, __DIR__.'/'.$file);
$ending = "\r\n";
$boundary = md5(microtime());
$fullBoundary = sprintf("--%s%s", $boundary, $ending);
$body = '';
$body .= $fullBoundary;
$body .= "Content-Disposition: form-data; name=\"image\"; filename=\"$file\"".$ending;
$body .= "Content-Type: $finfo".$ending;
$body .= "Content-Transfer-Encoding: base64".$ending.$ending;
$body .= chunk_split(base64_encode(file_get_contents(__DIR__.'/'.$file))).$ending;
$body .= "--".$boundary."--".$ending.$ending;
$ch = curl_init();
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
[
'Authorization: Bearer token...',
"Content-Type: multipart/form-data; boundary=".$boundary,
]
);
curl_setopt($ch, CURLOPT_URL, "http://api.example.com/upload");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0');
$curl_response = curl_exec($ch);
print_r(curl_getinfo($ch));
print_r($curl_response);
curl_close($ch);
谁能帮我解决这个问题?
附:我忘了说我尝试使用“@”表示法和 \CurlFile 但后来 $_FILES 数组为空,这就是我手动创建整个请求正文的原因。
【问题讨论】:
标签: php rest curl file-upload php-7