gpt4 book ai didi

php - 使用 php/curl 将图像上传到 tumblr 时出现的问题

转载 作者:行者123 更新时间:2023-12-04 06:44:53 25 4
gpt4 key购买 nike

我一直在尝试创建一个简单的 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 上:

File uploads can be done in a data parameter where specified above. You may use either of the common encoding methods:

1) multipart/form-data method, like a file upload box in a web form. Maximum size:

...10 MB for photos...

This is recommended since there's much less overhead.

2) Normal POST method, in which the file's entire binary contents are URL-encoded like any other POST variable. Maximum size:

...5 MB for photos...



谢谢。

最佳答案

尝试这个:

// 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。

关于php - 使用 php/curl 将图像上传到 tumblr 时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com