php - 通过 Tumblr API 上传多张图片

标签 php api filesystems tumblr

我有大约 300 张图片要上传到我的新 Tumblr 帐户,因为我的旧 wordpress 网站被黑了,我不想再使用 wordpress。

我连续 300 天每天上传一张图片,我希望能够拍摄这些图片并使用 api 将它们上传到我的 tumblr 网站。

图片目前是本地的,存储在/images/。它们都将上传日期作为文件名的前十个字符 (01-01-2009-filename.png),我也发送了这个日期参数。我希望能够通过将 API 的响应输出到我的 error_log 来查看脚本的进度。这是我目前所拥有的,基于 tumblr api 页面。

// Authorization info
$tumblr_email    = 'me@example.com';
$tumblr_password = 'password';

// Tumblr script parameters
$source_directory = "images/";

// For each file, assign the file to a pointer

这是第一个绊脚石。如何获取目录中的所有图像并循环遍历它们?一旦我设置了 for 或 while 循环,我认为这是下一步

$post_data = fopen(dir(__FILE__) . $source_directory . $current_image, 'r');
$post_date = substr($current_image, 0, 10);


// Data for new record
$post_type  = 'photo';

// Prepare POST request
$request_data = http_build_query(
    array(
        'email' => $tumblr_email,
        'password' => $tumblr_password,
        'type' => $post_type,
        'data' => $post_data,
        'date' => $post_date,
        'generator' => 'Multi-file uploader'
    )
);

// 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);

// Output response to error_log
error_log($result);

因此,我陷入了如何使用 PHP 读取文件目录、遍历每个文件以及对文件本身的名称/执行操作的问题。我还需要知道如何设置数据参数,例如选择 multi-part/formdata。我对 cURL 也一无所知。

最佳答案

您可以使用 glob 函数快速获取与模式匹配的文件数组。即:

foreach (glob('images/*.png') as $current_image) {
  ...
}

要使 curl 上传文件,您可以简单地向它传递以 @ 为前缀的文件名(请参阅 http://www.php.net/curl_setopt 处的 CURLOPT_POSTFIELDS 描述)。在你向它传递一个 PHP 文件句柄的那一刻,这没有多大意义。将 $post_data 更改为:

$post_data = '@' . dirname(__FILE__) . '/' . $current_image;

你应该很好。

关于php - 通过 Tumblr API 上传多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2869883/

相关文章:

api - Solr 可以加载原始 Lucene 索引吗?

linux - 在 Linux 文件系统中创建循环

php - 如何在 foreach 循环中选择 "sub-array"

php - Php Imagick来自可变中心点的裁剪图像

php - MySQL @grouping results by ID and sorting them by score”问题

php - 如何自定义 Wordpress 中日期戳的外观?

azure - 将 webAPI 发布到 Azure 时出现错误

ruby-on-rails - 如何为(所有)Rails 生成 RDOC?

.net - 最快的搜索技术/方法是什么? (在文件搜索的上下文中)

c - 获取文件的绝对路径