Domanda

So, my authentication process is asynchronous. I need upload file but, I don't know how I can add 'multipart/form-data' BodyParser parameter to action.

This is Secured trait:

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)
      }
    }
}

I'm trying this:

  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)
    }
  }

but, did not work.

in Controller:

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

Anybody knows how to make it?

Thanks in advance!

È stato utile?

Soluzione

You should to write in your Auth method like this:

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

And then You may upload with this way in 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
  }
}

Altri suggerimenti

What if you tried Action.async(b) instead of Action(b).async?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top