mardi 21 avril 2015

play framework form binding with body parsers failure

I have a problem with multipartFormData. I want to send a form with files. The files have a size limitation. After adding the maxLength it seems the data from the Form is somehow lost. The file size validations works however.

This is my code - 2 options:

def addFormWithFiles = Action(parse.maxLength(10 * 1024 * 1024,parse.multipartFormData)) {implicit request =>
    //Option 1
    request.body match {
      case Left(_) => BadRequest("The file you attached was too large")
      case Right(multipartdata) =>
        sampleForm.bindFromRequest().fold(
          hasErrors => Ok(hasErrors),
          goodThingy => {
            multipartdata.file("myFile") match {
              case Some(file) =>
                import java.io.File
                file.ref.moveTo(new File("PATH"))
                MyDAO.insert(goodThingy)
                Ok("File injection good, and form good")
              case _ => Ok("at least the form is good, but no file")
        }
      }
    )
}

// Option 2
sampleForm.bindFromRequest().fold(
hasErrors => {
  request.body match {
    case Left(_) => Ok(hasErrors)
    case Right(_) => Ok(hasErrors)
  }
},
goodThingy =>
  request.body match {
      // file too big but the form is ok
    case Left(_) => Ok(goodThingy)
    case Right(multipartform) => multipartform.file("myFile") match {
      case Some(file) =>
        import java.io.File
        file.ref.moveTo(new File("path"))
        MyDAO.insert(goodThingy)
        Ok("adding file and item to db success")
      case _ =>
        MyDAO.insert(goodThingy)
        Ok("at least the form was good, no file attached")

    }
  }
)
  }

Aucun commentaire:

Enregistrer un commentaire