Search code examples
rcurlhttr

Specify Filename in {httr} File Upload


I am trying to translate the following (working) curl query into {httr} code:

CURL=`which curl`
$CURL -H "Accept: application/json" \
      -F "token=TOKEN_TOKEN" \
      -F "content=file" \
      -F "action=import" \
      -F "record=1" \
      -F "field=file_upload" \
      -F "file=@old.txt;filename=new.txt" \
      https://somewhere.com/api/

The following does not work as the server ignores the filename when submitted as what amounts to an additional form element.

httr::POST(
  url = "https://somewhere.com/api/",
  body = list(
    "token"    = "TOKEN_TOKEN",
    "content"  = "file",
    "action"   = "import",
    "record"   = "1",
    "field"    = "file_upload",
    "file"     = httr::upload_file("old.txt"),
    "filename" = "new.txt"
  ),
  encode = "multipart"
)

Is there some way to specify the new filename instead of having the filename inferred from the original file's name?


Solution

  • Alternate file name specification is now supported.

    httr

    httr::POST(
      url = "https://somewhere.com/api/",
      body = list(
        "token"    = "TOKEN_TOKEN",
        "content"  = "file",
        "action"   = "import",
        "record"   = "1",
        "field"    = "file_upload",
        "file"     = curl::form_file("old.txt", name = "new.txt")
      ),
      encode = "multipart"
    )
    

    httr2

    httr2::request("https://somewhere.com/api/") %>% 
      httr2::req_body_multipart(
        token    = "TOKEN_TOKEN",
        content  = "file",
        action   = "import",
        record   = "1",
        field    = "file_upload",
        file     = curl::form_file("old.txt", name = "new.txt")
      ) %>% 
      httr2::req_perform()