在Play 2.2.1 Framework中使用带有经过身份验证的请求的BodyParser

时间:2013-12-05 10:52:00

标签: scala-2.10 playframework-2.2

所以,我的身份验证过程是异步的。我需要上传文件,但我不知道如何将'multipart / form-data'BodyParser 参数添加到操作中。

这是安全特质:

trait Secured {

  private def username(request: RequestHeader) = request.session.get("email")

  private def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Auth.login)

  def IsAuthenticated(f: => String => Request[AnyContent] => Future[SimpleResult]) =
    Security.Authenticated(username, onUnauthorized) { user =>
      Action.async { request =>
        f(user)(request)
      }
    }
}

我正在尝试这个:

  def IsAuthenticated(b: BodyParser[AnyContent] = parse.anyContent)(f: => String =>
  Request[AnyContent] => Future[SimpleResult]) = 
  Security.Authenticated(username, onUnauthorized) { user =>
    Action(b).async { request =>
      f(user)(request)
    }
  }

但是,没有用。

控制器中的

def upload = IsAuthenticated { _ => implicit request =>
  request.body.moveTo(new File("/tmp/picture/uploaded"))
  Future.successful(Ok("File uploaded"))
}

有人知道怎么做吗?

提前致谢!

2 个答案:

答案 0 :(得分:2)

您应该像这样写下您的Auth方法:

def IsAuthenticated[A](b: BodyParser[A])(f: => String => Request[AnyContent] => Future[SimpleResult]) = 
  Security.Authenticated(username, onUnauthorized) { user =>
  Action.async { request =>
    f(user)(request)
  }
}

然后您可以在Controller中以这种方式上传:

def upload = IsAuthenticated(parse.temporaryFile) {_ => implicit request =>
  val mfData = request.body.asMultipartFormData
  Future.successful {
    mfData.map { tempFile =>
      tempFile.file("picture").map { file =>
        val filePath = new File(".").getCanonicalPath() + "/test.png"
        file.ref.moveTo(new File(filePath), true)
        Logger.info("File successfully received to:" + filePath + " folder")
        Ok("File uploaded")
      }.getOrElse {
        Redirect(routes.Application.uploadWindow()).flashing("error" -> "Missing file")
      }
    }.get
  }
}

答案 1 :(得分:1)

如果您尝试Action.async(b)而不是Action(b).async怎么办?