How to POST multipart/related content with httr (for Google Drive API)

旧巷老猫 提交于 2019-12-01 17:42:31

You shoud be able to do this using curl::form_file or its alias httr::upload_file. See also the curl vignette. Following the example from the Google API doc:

library(httr)

media <- tempfile()
png(media, with = 800, height = 600)
plot(cars)
dev.off()

metadata <- tempfile()
writeLines(jsonlite::toJSON(list(title = unbox("My file"))), metadata)

#post
req <- POST("https://httpbin.org/post",
  body = list(
    metadata = upload_file(metadata, type = "application/json; charset=UTF-8"),
    media = upload_file(media, type = "image/png")
  ),
  add_headers("Content-Type" = "multipart/related"),
  verbose()
)

unlink(media)
unlink(metadata)

The only difference here is that curl will automatically add a Content-Disposition header for each file, which is required for multipart/form-data but not for multipart/related. The server will probably just ignore this redundant header in this case.

For now there is no way to accomplish this without writing the content to a file. Perhaps we could add something like that in a future version of httr/curl, although this has not come up before.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!