Max file upload size in Play framework 2.0

2020-02-08 07:02发布

问题:

When I upload large files (greater than 1 MB) in play framework 2.0 I get

"413 Request Entity Too Large" error.

Could you please anybody suggest how to get rid of this?

Thanks,

UPDATE I have solved this issue by adding this to application.conf

#Set Max file size

parsers.MultipartFormData.maxLength=10240K

回答1:

See http://www.playframework.com/documentation/2.0.x/ScalaBodyParsers

or Java version: http://www.playframework.com/documentation/2.0.x/JavaBodyParsers

extract:

// Accept only 10KB of data.
def save = Action(parse.text(maxLength = 1024 * 10)) { request =>
  Ok("Got: " + text)
}

And you can configure this in your application.conf using parsers.text.maxLength.



回答2:

parse.multipartFormData and parse.temporaryFile don't take maxLength as argument letting you increase or decrease the default like parse.text(maxLength) does.

But you can use parse.maxLength(maxLength, wrappedBodyParser) instead:

// accepts 10 MB file upload
def save = Action(parse.maxLength(10 * 1024 * 1024, parse.multipartFormData)) { request =>
    request.body match {
        case Left(MaxSizeExceeded(length)) => BadRequest("Your file is too large, we accept just " + length + " bytes!")
        case Right(multipartForm) => {
            /* Handle the POSTed form with files */
            ...
        }
    }
}


回答3:

For play version 2.4.x:

For parsers that buffer content on disk, such as the raw parser or multipart/form-data, the maximum content length is specified using the play.http.parser.maxDiskBuffer property, it defaults to 10MB. The multipart/form-data parser also enforces the text max length property for the aggregate of the data fields.

https://www.playframework.com/documentation/2.4.x/ScalaBodyParsers



回答4:

In my case, I got the error on an AJAX request (It was a long text). For requests like this, you can set the property:

parsers.text.maxLength=1024K

More information on play documentation: https://www.playframework.com/documentation/2.0/JavaBodyParsers



回答5:

I am using an AnyContent Parser. I had to change to controller code to following as the configurations didn't work for me

 def newQuestion = silhouette.SecuredAction.async(parse.maxLength(1024 * 1024, parse.anyContent)(ActorMaterializer()(ActorSystem("MyApplication")))) { 
    implicit request => {
      println("got request with body:" + request.body)
      val anyBodyErrors: Either[MaxSizeExceeded, AnyContent] = request.body
      anyBodyErrors match {
        case Left(size) => {
          Future {
            EntityTooLarge(Json.toJson(JsonResultError(messagesApi("error.entityTooLarge")(langs.availables(0)))))
          }
        }
        case Right(body) => {

          //val body:AnyContent = request.body
          val jsonBodyOption = body.asJson
}
}