首页 > 解决方案 > 从 R 将图像上传到 wordpress 库

问题描述

任何人都试图使用 R 中的 POST 命令通过 REST API 将图像上传到 wordpress。

我认为这会做到,但没有雪茄。

POST(paste0(site,"wp/v2/media"),              
add_headers(
          'Authorization' = paste("Bearer", token, sep = " "), 
          'cache-control' = "no-cache", 
          'content-disposition' = "attachment; filename=test.png",
          'content-type' = "image/png"), 
      body = list(
        title = "page_title", 
        status = "published", 
      encode = "json") 
)

标签: rwordpressrest

解决方案


POST /wp/v2/media通过端点创建新附件可以通过两种方式完成:

  1. Content-Dispositionheader 设置为attachment; filename=<file name>,并将Content-Typeheader 设置为正确的 MIME 类型,例如image/jpeg,然后将请求正文设置为二进制文件内容。

  2. Content-Type标头设置为multipart/form-data; boundary=<boundary>,然后将请求正文设置为多部分数据,如您在此处看到的,以 . 开头---------------------------<boundary>和结尾---------------------------<boundary>--

    特别是对于 WordPress,使用此选项的优点是您可以设置自定义附件帖子数据,如帖子标题和 slug。但请确保媒体文件的表单数据名称是准确的file- 而不是filedatafile_content或其他名称。

在 R 中,您可以轻松地执行上述操作,并将Authorization标头设置为Bearer <token>,并且我们正在上传 JPEG 图像:

基于上述选项 1 的示例

r <- POST(
    'https://example.com/wp-json/wp/v2/media',
    add_headers(
        'Authorization' = paste('Bearer', token, sep = ' '),
        'Content-Disposition' = 'attachment; filename="test-using-R-4.0.4.jpg"',
        'Content-Type' = 'image/jpeg'
    ),
    body = upload_file('test.jpg', 'image/jpeg')
)
d <- content(r)

cat( ifelse(! is.null(d[['id']]),
    paste('success - id:', d['id']),
    paste('error:', d['message']))
)

基于上述选项 2 的示例

r <- POST(
    'https://example.com/wp-json/wp/v2/media',
    add_headers(
        'Authorization' = paste('Bearer', token, sep = ' '),
    ),
    body = list(
        file = upload_file('test.jpg', 'image/jpeg'),
        title = 'custom title',
        slug = 'custom-slug'
    )
)
d <- content(r)

cat( ifelse(! is.null(d[['id']]),
    paste('success - id:', d['id']),
    paste('error:', d['message']))
)

如果您使用的是 WordPress 5.6 中引入的默认应用程序密码功能,那么您将希望使用authenticate()而不是add_headers()上面选项 2 中的:

# Replace this:
add_headers(
    'Authorization' = paste('Bearer', token, sep = ' '),
),

# with this one:
authenticate('<your WordPress username>', '<your WordPress Application Password>'),

因此,我希望这些在 R-4.0.4 上经过尝试和测试的示例也对您有用。


推荐阅读