1

我有下一个 Scala 函数:

  def upload = Action(parse.multipartFormData)  { implicit request =>
//grabbing the values from the request
println("Request To Upload File = " + request.toString)
val values = request.body.dataParts
val category:Option[Seq[String]] = values.get("category")
val id:Option[Seq[String]] = values.get("id")


//Grabbing the parts of the file, and adding that into the logic
request.body.file("file").map { file =>
  val fileBytes = FileUtils.readFileToByteArray(new File(file.ref.file.getPath))
  val fileType = file.contentType.getOrElse("None")
  val encodedFile:String = Base64.getEncoder().encodeToString(fileBytes)
  val rowId = getElement(id)
  println(rowId)
  val record:FileRecord = FileRecord(rowId, getElement(userid), file.filename, getElement(category),getElement(project), "1",fileType,encodedFile,0)
  FileRecords.add(record)
  Ok(rowId)
}.getOrElse {
  BadRequest("Dragons won.")
}

}

我想创建一个将使用此功能的 axios 帖子。就像是:

           axios.post('/upload', {id: someId, 
                                  category: someCategory,
                                  file: someUploadedFile
                                  })
                                .then((response) => {.... })

someUploadedFile 来自:

    var componentConfig = { postUrl: 'no-url' };
var djsConfig = { autoProcessQueue: false }

var eventHandlers = { addedfile: (someUploadedFile) => ... code to upload file with axios.post ..... }

ReactDOM.render(
    <DropzoneComponent config={componentConfig}
                       eventHandlers={eventHandlers}
                       djsConfig={djsConfig} />,
    document.getElementById('content')
);

我的大问题是,既然包含了一个文件,我不明白如何构建该 axios 调用,并且还添加了与该文件相关的更多信息,因此 Scala 函数中的请求对象将能够从 json 处理该文件。

4

1 回答 1

2

使用 FormData 发布文件,如下所示:

var formData = new FormData();
formData.append('file', someUploadedFile);
formData.append('otherAttribute', 'someValue');

axios.post('/upload', formData).then(...)
于 2018-11-18T18:03:43.153 回答