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

后端 未结 1 1283
迷失自我
迷失自我 2021-01-18 15:10

I got simple file uploads to Google Drive working using httr. The problem is that every document is uploaded as \"untitled\", and I have to PATCH the metadata to set the tit

相关标签:
1条回答
  • 2021-01-18 15:54

    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.

    0 讨论(0)
提交回复
热议问题