2014-04-29 36 views
2

我试图检查Play应用程序(2.0.3)中上传的文件的大小。Play Framework 2.0中的文件大小限制

我试过了Scala和Java控制器,但每次都有同样的奇怪行为......我设法检测到文件太大,但是当我尝试返回响应时,请求会永远挂起并且用户不知道该请求无效。

在Java:

@BodyParser.Of(value = BodyParser.MultipartFormData.class, maxLength = 10 * 1024 * 1024) 
pulic static Result upload() { 
    if(request().body().isMaxSizeExceeded()) { 
    return badRequest("Too much data!"); // this is not returned 
    } else { 
    ok("Got body: " + request().body().asText()); 
    } 
} 

在斯卡拉:

def upload = Action(parse.maxLength(10 * 1024 * 1024, parse.multipartFormData)) { request => 
    request.body match { 
     case Left(MaxSizeExceeded(length)) => { 
      Logger.error("MaxSizeExceeded") 
      BadRequest("Your file is too large, we accept just " + length + " bytes!") 
     } 
     case Right(multipartForm) => { 
      // Do stuff to handle the file 
     } 
    } 
} 

HTML模板:

@(httpPath: java.lang.String) @main(httpPath) { 

    @helper.form(action = routes.Application.upload(), 'enctype -> "multipart/form-data", 'class -> "form-horizontal", 'id -> "form") { 

     <div id="well" class="well"> 

       <h1>Upload</h1> 
       <div id="formGroup" class="control-group"> 
        <label class="control-label" for="file">Select file : </label> 
        <div class="controls"> 
         <input id="file" name="file" type="file" style="display: none" /> 

         <div class="input-append"> 
          <input id="txtFile" type="text" class="required" readonly="true"/> 
          <span class="btn" onclick="$('#file').click();">Browse</span> 
         </div> 

         <script type="text/javascript"> 
          $('#file').change(function() { 
           $('#txtFile').val($(this).val()); 
          }); 
         </script> 
        </div> 
       </div> 

       <button id="submit" type="submit" class="btn btn-primary" >Upload</button> 
     </div> 
    } 
} 

登录:

2014-04-30 16:46:44,791 - [[trace]] - play - New I/O worker #4 - Serving this request with: Action(parser=BodyParser(maxLength=1048576, wrapping=BodyParser(multipartFormData))) - 
2014-04-30 16:46:44,996 - [[trace]] - play - play-akka.actor.promises-dispatcher-60 - Invoking action with request: POST /upload - 
2014-04-30 16:46:44,998 - [[error]] - application - play-akka.actor.actions-dispatcher-10 - MaxSizeExceeded java - 
2014-04-30 16:46:44,999 - [[trace]] - play - play-akka.actor.actions-dispatcher-10 - Sending simple result: SimpleResult(400, Map(Content-Type -> text/plain; charset=utf-8, Set-Cookie ->)) - 

我看到其他开发者面临同样的问题(例如https://groups.google.com/forum/#!topic/play-framework/wuXnoXN5GZ0)。 这是2.0.x中的一个已知问题吗?难道我做错了什么?

谢谢

+0

你能在Play 2.2.x中试用你的代码,看看它在那里工作吗?这将告诉我们这是否是自Play 2.0.x以来已解决的问题。 –

+0

我已经试过2.0.8,但同样的问题。 不幸的是,我不得不为这个应用程序使用2.0.x版本,但我仍然会尝试。 –

+0

即使在2.2.1中,请求也会挂起。 当文件太大并且您想终止请求时,结束请求的正确方法是什么? –

回答

1

通过将Play版本升级到2.2.1,问题消失。

我试着发布最后的2.0.x版本(2.0.8),这个bug仍然存在。

显然,它已经在2.1.x中修复。