r - 从 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")
)
解决方案
POST /wp/v2/media
通过端点创建新附件可以通过两种方式完成:
将
Content-Disposition
header 设置为attachment; filename=<file name>
,并将Content-Type
header 设置为正确的 MIME 类型,例如image/jpeg
,然后将请求正文设置为二进制文件内容。将
Content-Type
标头设置为multipart/form-data; boundary=<boundary>
,然后将请求正文设置为多部分数据,如您在此处看到的,以 . 开头---------------------------<boundary>
和结尾---------------------------<boundary>--
。特别是对于 WordPress,使用此选项的优点是您可以设置自定义附件帖子数据,如帖子标题和 slug。但请确保媒体文件的表单数据名称是准确的
file
- 而不是filedata
,file_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 上经过尝试和测试的示例也对您有用。
推荐阅读
- java - Spring Security 和 Angular 6 HTTPS 请求
- php - Symfony 2 表单主题相关实体
- javascript - 如何从 5 天天气预报 JS 中获取当天的最低和最高温度?
- c# - 模拟的 SignInManager 没有按预期工作
- html - 如何使旁边的列随着并行列中内容的大小而增长
- npm - npm 错误!代码 E407 需要代理身份验证
- ssl - 证书管理器使用 gitlab autodevops 无法进入 kubernetes 集群
- ios - 无法使用 json 数据填充 UITableview
- android - 禁用或启用 chrome 会导致我在后台的 android 应用程序在恢复时崩溃
- javascript - 如何获得动态高度