API 以文件作为输入参数

API that takes a file as input parameter

我被要求创建一个 API 将文件作为输入并将该文件放在服务器上的目录中。这是为了消除应用程序直接与文件夹交互的需要。

我以前构建过 APIs(在 R 中使用 Plumber)并且可以处理字符串输入 - 我只是难以接受一个文件作为输入参数。管道工文档的 None 解释了如何执行此操作。这甚至可以做到吗?在 Python 中有没有办法做到这一点?

您可以使用 plumberRook 使用 POST 上传文件。

这是一个小例子

api.R

library(plumber)
library(Rook)

#* Upload file
#* @param upload File to upload
#* @post /uploadfile
function(req, res){
  fileInfo <- list(formContents = Rook::Multipart$parse(req))
  ## The file is downloaded in a temporary folder
  tmpfile <- fileInfo$formContents$upload$tempfile
  ## Copy the file to a new folder, with its original name
  fn <- file.path('~/Downloads', fileInfo$formContents$upload$filename)
  file.copy(tmpfile, fn)
  ## Send a message with the location of the file
  res$body <- paste0("Your file is now stored in ", fn, "\n")
  res
}

运行 服务器

plumber::plumb('api.R')$run(port = 1234)

使用 curl 发送文件 test.txt

curl -v -F upload=@test.txt http://localhost:1234/uploadfile