【发布时间】:2014-06-15 10:48:45
【问题描述】:
我正在尝试检查在 Play 应用程序 (2.0.3) 中上传的文件的大小。
我尝试了 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());
}
}
在 Scala 中:
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 中的一个已知问题吗?我做错了吗?
谢谢
【问题讨论】:
-
您能否在 Play 2.2.x 中尝试您的代码,看看它是否在那里工作?这将告诉我们这是否是自 Play 2.0.x 以来已修复的问题。
-
我已经尝试过 2.0.8,但同样的问题。不幸的是,我必须为这个应用程序使用 2.0.x 版本,但我还是要试试。
-
即使在 2.2.1 中,请求也会挂起。当文件太大并且您想终止请求时,结束请求的正确方法是什么?
-
你能展示你的视图模板(html文件)吗?
-
我刚刚用模板编辑了问题
标签: java scala file-upload playframework playframework-2.0