如何在httr包中传递curl -F参数?

How to pass the curl -F parameter in the httr package?

您好,我尝试使用 httr 翻译此 curl 指令

curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=@test.txt -F filename=test.txt -F parent_dir=/ http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3

没有 -F 参数的指令是:

httr::POST(
  url = "http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3",
  add_headers(Authorization = "Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd")
  )
)

我想我必须使用 httr::upload_file 函数,但我没有成功地使用它。

你知道我该怎么做吗?

此致

下面是如何使用 httr 包构建这个 curl 请求。我使用 httpbin.org 来测试发送的请求。

您将使用 POST 用列表填充正文。 encode 参数控制此列表的处理方式,默认情况下它是您需要的正确 multipart

res <- httr::POST(
  url = "http://httpbin.org/post",
  httr::add_headers(Authorization = "Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd"),
  # Add the file and metadata as body using a list. Default encode is ok
  body = list(
    file = httr::upload_file("test.txt"),
    filename = "test.txt",
    parent_dir = "/"
  )
)

httr_ouput <- httr::content(res)

检查是否正常的一种方法是将输出与您知道正在运行的 curl 命令进行比较

out <- sys::exec_internal(
       'curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=@test.txt -F filename=test.txt -F parent_dir=/ http://httpbin.org/post'
    )
curl_output <- jsonlite::fromJSON(rawToChar(out$stdout))

#compare body

identical(curl_output$files, httr_ouput$files)
#> TRUE
identical(curl_output$form, httr_ouput$form)
#> TRUE

您也可以使用 crul 包来完成,这是 curl 之上的另一个包装器;逻辑相同

con <- crul::HttpClient$new(
  url = "http://httpbin.org/post"
)

crul_req <- con$post(
  body = list(
    file = crul::upload("test.txt"),
    filename = "test.ext",
    parent_dir = "/"
  )
)

crul_output <- jsonlite::fromJSON(crul_req$parse())