I want to POST a request to upload a file (a png in this case) with httr2 in R.
This example uses upload_file() of the superseded package httr (found in this answer):
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)
In the httr2's doc, I could find this example that uses req_body_json:
req <- req_gist(token) %>%
req_body_json(list(
description = "This is my cool gist!",
files = list(test.R = list(content = "print('Hi!')")),
public = FALSE
))
req %>% req_dry_run()
But this sends some text in the body and I want to upload a file.
What is the equivalent of httr:upload_file in httr2?
As usual, I should look at the doc.
It's the function
req_body_file(req, path, type = NULL):