我一直在尝试创建一个简单的php文件,将单个图像上传到tumblr。列出了一个示例here,但它不适用于图像。这是代码:
<?php
// Authorization info
$tumblr_email = 'lol@something.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'photo';
//////////////////////THIS DOESN'T WORK/////////////////////////////////
//$filename = "/Applications/MAMP/htdocs/1.jpeg";
//$handle = fopen($filename, "r");
//$post_data = fread($handle, filesize($filename));
//////////////////////NEITHER DOES THIS/////////////////////////////////
//$post_data = "/Applications/MAMP/htdocs/1.jpg";
///////////////////////////////NOR THIS/////////////////////////////////
//$filename = "/Applications/MAMP/htdocs/1.jpeg";
//$post_data = fopen($filename, "r");
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'data' => $post_data,
'generator' => 'testing tumblr API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
?>
我不熟悉php / curl,所以我不知道我做错了什么。这也写在tumblr.com上:
文件上传可以在上面指定的数据参数中完成。您可以使用以下任一常用编码方法:
1)multipart / form-data方法,就像Web表单中的文件上传框一样。最大尺寸:
... 10 MB的照片...
建议这样做,因为开销要少得多。
2)正常的POST方法,其中文件的整个二进制内容像任何其他POST变量一样进行URL编码。最大尺寸:
... 5 MB照片...
感谢。
答案 0 :(得分:4)
试试这个:
// Authorization info
$tumblr_email = 'lol@something.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'photo';
$post_data = "/Applications/MAMP/htdocs/1.jpg";
$request_data = array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'data' => '@'.$post_data,
'generator' => 'testing tumblr API example'
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
您需要将数组传递给CURLOPT_POSTFIELDS,并使用@前置文件的绝对路径。这将使cURL将数据作为multipart / form-data发布。