Return multipart body with RestRserve?

111 Views Asked by At

Can RestRserve return multiple files via multipart/form-data? I've tried using set_body(c("file"=path)) and it returns the file content as per documentation. This doesn't work with several files, however, as a list of filenames will be returned and not their content.

# load packages
library(readr)
library(callr)
library(httr)

# run RestRserve in the background
ps <- r_bg(function() {
  library(RestRserve)
  library(readr)

  app = Application$new()

  app$add_get(path = "/oneFile", FUN = function(request, response) {
    tmp1 <- tempfile(fileext = ".csv")
    write_csv(head(iris, 3), tmp1)
    response$set_body(c("file"=tmp1))
  })

  app$add_get(path = "/twoFiles", FUN = function(request, response) {
    tmp1 <- tempfile(fileext = ".csv")
    write_csv(head(iris, 3), tmp1)
    tmp2 <- tempfile(fileext = ".csv")
    write_csv(tail(iris, 3), tmp2)  
    response$set_body(c("file"=tmp1, "file"=tmp2))
  })

  backend = BackendRserve$new()
  backend$start(app, http_port = 65080)
})

# wait for up
Sys.sleep(2L)

# check is alive
ps$is_alive()

# test endpoints
rs1 <- GET(url = "http:/127.0.0.1:65080/oneFile")
cat(content(rs1, encoding = 'UTF-8'))
#> Sepal.Length,Sepal.Width,Petal.Length,Petal.Width,Species
#> 5.1,3.5,1.4,0.2,setosa
#> 4.9,3,1.4,0.2,setosa
#> 4.7,3.2,1.3,0.2,setosa

rs2 <- GET(url = "http:/127.0.0.1:65080/twoFiles")
cat(content(rs2, encoding = 'UTF-8'))
#> C:\Users\platinov\AppData\Local\Temp\RtmpekJ82H\file211c79eec27.csv
#> C:\Users\platinov\AppData\Local\Temp\RtmpekJ82H\file211c68243bc6.csv

# kill background prcoess
ps$kill()
rm(ps)
0

There are 0 best solutions below