如何查找通过 Dropwizard REST 上传的文件的大小 API

How to find the size of a file uploaded via Dropwizard REST API

我正在使用 Dropwizard 0.7.0 构建一个 API 用于文件上传。 运行 验证上传文件大小限制时遇到问题。我想在将文件写入磁盘之前检查大小

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response uploadFile(@Context final HttpServletRequest request, @FormDataParam("file") FormDataBodyPart fileBodyPart) {

    /*
     * Check the request size
     */
    request.getPart("file").getSize();
.........
}

它抛出一个错误:

java.lang.IllegalStateException: No multipart config for servlet
at org.eclipse.jetty.server.Request.getParts(Request.java:2075) ~[jetty-  server-9.0.7.v20131107.jar:9.0.7.v20131107]
at org.eclipse.jetty.server.Request.getPart(Request.java:2055) ~[jetty-server-9.0.7.v20131107.jar:9.0.7.v20131107]

编辑 ----------------------

@大卫

已升级到 dropwizard 0.8.0 但是 运行 出现另一个错误

com.sun.jersey.spi.inject.Errors: The following errors and warnings have been detected with resource and/or provider classes:
org.glassfish.jersey.media.multipart.file.FormDataBodyPart
org.glassfish.jersey.media.multipart.file.FileDataBodyPart
org.glassfish.jersey.media.multipart.FormDataContentDisposition

使用这些依赖项

<dependency>
 <groupId>io.dropwizard</groupId>
 <artifactId>dropwizard-forms</artifactId>
 <version>${dropwizard.version}</version>
</dependency> 

<dependency>
 <groupId>org.glassfish.jersey.media</groupId>
 <artifactId>jersey-media-multipart</artifactId>
 <version>2.23.2</version>
</dependency>

已添加

bootstrap.addBundle(new MultiPartBundle());

还有这个(第一次失败后)

env.jersey().register(MultiPartFeature.class);

我在这里错过了什么?

能够提交多部分数据需要额外的 dropwizard 依赖项。对于 0.8 及更高版本,依赖项为 dropwizard-forms.

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-forms</artifactId>
    <version>${dropwizard.version}</version>
</dependency>

http://www.dropwizard.io/0.8.0/docs/manual/forms.html

用法示例:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
        @FormDataParam("myFileName") InputStream file,
        @FormDataParam("myFileName") FormDataContentDisposition fileMetaData
){

    long fileSize = fileMetaData.getSize();
    // etc
}

这就是我正在使用的。也许升级是您的解决方案。

如果没有,dropwizard 0.7 是可行的,但我还没有这样做...从快速 google 来看,您似乎需要以下依赖项:

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.18.1</version>
</dependency>

... 并将以下内容添加到您的应用程序 run 方法中:

environment.jersey().register(MultiPartFeature.class);

考虑到错误 "No multipart config for servlet" 我假设你的上传根本不起作用,没有你的尺寸检查?