使用Jersey-1.7在Google Appengine上进行多部分文件上传

11

我在Google Appengine上使用Jersey编写了一个处理简单文件上传的应用程序。当它使用Jersey 1.2版本时,一切都很好。在后续版本(当前为1.7)中引入了@FormDataParam来处理multipart/form输入。我正在使用jersey-multipart和mimepull依赖项。现在的做法似乎是在appengine中创建临时文件,我们都知道这是不合法的...

我是否遗漏了什么或者做错了什么,因为Jersey现在应该与AppEngine兼容了吗?

@POST 
@Path("upload") 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
public void upload(@FormDataParam("file") InputStream in) { .... }

当使用以下异常调用时,上述方法将失败...

/upload
java.lang.SecurityException: Unable to create temporary file
    at java.io.File.checkAndCreate(File.java:1778)
    at java.io.File.createTempFile(File.java:1870)
    at java.io.File.createTempFile(File.java:1907)
    at org.jvnet.mimepull.MemoryData.createNext(MemoryData.java:87)
    at org.jvnet.mimepull.Chunk.createNext(Chunk.java:59)
    at org.jvnet.mimepull.DataHead.addBody(DataHead.java:82)
    at org.jvnet.mimepull.MIMEPart.addBody(MIMEPart.java:192)
    at org.jvnet.mimepull.MIMEMessage.makeProgress(MIMEMessage.java:235)
    at org.jvnet.mimepull.MIMEMessage.parseAll(MIMEMessage.java:176)
    at org.jvnet.mimepull.MIMEMessage.getAttachments(MIMEMessage.java:101)
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:177)
    at com.sun.jersey.multipart.impl.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:80)
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:139)
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:77)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:474)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:538)

有人知道吗?是否有一种方法可以在防止mimepull创建临时文件的同时完成这个事情?

5个回答

17
对于超出默认大小的文件,multipart 将创建一个临时文件。为了避免这种情况(在GAE上创建文件是不可能的),您可以在项目的资源文件夹中创建一个 jersey-multipart-config.properties 文件,并将以下行添加到其中:
bufferThreshold = -1

然后,代码就是你提供的那个:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response post(@FormDataParam("file") InputStream stream, @FormDataParam("file") FormDataContentDisposition disposition) throws IOException {
  post(file, disposition.getFileName());
  return Response.ok().build();
}

1
有什么想法可以用程序实现吗? - gk5885
7
谢谢你的解决方案。只是提醒一下,如果你正在使用Jersey 2+,你需要将jersey.config.multipart.bufferThreshold作为属性名称。 - David Welch
4
请问资源文件夹 resources 应该放在哪里?是放在 \war 目录下还是 \WEB-INF 目录下或其他地方?谢谢。 - Floris
非常感谢,这让我的一天都变得美好了...我为解决这个问题苦苦挣扎了相当长的时间。再次感谢! - Indraneel
这似乎是答案。 - I.Tyger
显示剩余3条评论

11

为了帮助在使用Eclipse和GPE(Google Plugin for Eclipse)时遇到困难的人们,我提供这个稍微修改过的解决方案,源自于 @yves 的答案。

我已经测试过它可以与App Engine SDK 1.9.10Jersey 2.12一起使用。 但由于其他不同的问题,它不能与App Engine SDK 1.9.6 -> 1.9.9等一起使用。

在你的\war\WEB-INF\classes文件夹下创建一个名为jersey-multipart-config.properties的新文件。编辑该文件,使其包含以下行jersey.config.multipart.bufferThreshold = -1

注意:在Eclipse中,\classes文件夹是隐藏的,因此请在操作系统的文件浏览器(例如Windows资源管理器)中查找该文件夹。

现在,在初始化multipart特性(在Jersey servlet初始化时)和进行文件上传(在Jersey servlet post请求时)时,将不再创建临时文件,因此GAE将不会出现问题。


1
谢谢你!在 bufferThreshold 之前加上 jersey.config.multipart. 解决了它!;) - DominikAngerer
1
对于想在eclipse中实现这个的人:是的,classes文件夹在“Package Explorer”视图中不会显示,但您仍可以使用_Navigator_视图访问它,而不是使用_Package Explorer_。 (从那里,您甚至可以右键单击并执行“在远程系统视图中显示”,以便探索底层文件系统。) - Amos M. Carpenter
你在App Engine上成功使用了Jersey 2吗?我以为它依赖于servlet-api:1.3.x。我知道这很老旧,但我很想看看你的依赖树... - ndtreviv

3

将文件jersey-multipart-config.properties放置在WAR包内的WEB-INF/classes目录下非常重要。

通常,在WAR文件结构中,您将配置文件(web.xmlappengine-web.xml)放在WEB-INF/中,但是在这里,您需要放在WEB-INF/classes目录下。

例如Maven配置:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archiveClasses>true</archiveClasses>
                <webResources>
                    <resource>
                        <directory>${basedir}/src/main/webapp/WEB-INF</directory>
                        <filtering>true</filtering>
                        <targetPath>WEB-INF</targetPath>
                    </resource>
                    <resource>
                        <directory>${basedir}/src/main/resources</directory>
                        <targetPath>WEB-INF/classes</targetPath>
                    </resource>
                </webResources>
            </configuration>
        </plugin>

你的项目结构可以如下所示:

项目结构

使用Jersey 2.x的jersey-multipart-config.properties文件内容:

jersey.config.multipart.bufferThreshold = -1

1
我已经找到了一种编程方法来避免使用临时文件的创建(对于GAE实现非常有用)。
我的解决方案是创建一个新的MultiPartReader Provider...以下是我的代码。
  @Provider
    @Consumes("multipart/*")
    public class GaeMultiPartReader implements MessageBodyReader<MultiPart> {

    final Log logger = org.apache.commons.logging.LogFactory.getLog(getClass());

    private final Providers providers;

    private final CloseableService closeableService;

    private final MIMEConfig mimeConfig;

    private String getFixedHeaderValue(Header h) {
        String result = h.getValue();

        if (h.getName().equals("Content-Disposition") && (result.indexOf("filename=") != -1)) {
            try {
                result = new String(result.getBytes(), "utf8");
            } catch (UnsupportedEncodingException e) {            
                final String msg = "Can't convert header \"Content-Disposition\" to UTF8 format.";
                logger.error(msg,e);
                throw new RuntimeException(msg);
            }
        }

        return result;
    }

    public GaeMultiPartReader(@Context Providers providers, @Context MultiPartConfig config,
        @Context CloseableService closeableService) {
        this.providers = providers;

        if (config == null) {
            final String msg = "The MultiPartConfig instance we expected is not present. "
                + "Have you registered the MultiPartConfigProvider class?";
            logger.error( msg );
            throw new IllegalArgumentException(msg);
        }
        this.closeableService = closeableService;

        mimeConfig = new MIMEConfig();
        //mimeConfig.setMemoryThreshold(config.getBufferThreshold());
        mimeConfig.setMemoryThreshold(-1L); // GAE FIX
    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return MultiPart.class.isAssignableFrom(type);
    }

    @Override
    public MultiPart readFrom(Class<MultiPart> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> headers, InputStream stream) throws IOException, WebApplicationException {
        try {
            MIMEMessage mm = new MIMEMessage(stream, mediaType.getParameters().get("boundary"), mimeConfig);

            boolean formData = false;
            MultiPart multiPart = null;

            if (MediaTypes.typeEquals(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE)) {
                multiPart = new FormDataMultiPart();
                formData = true;
            } else {
                multiPart = new MultiPart();
            }

            multiPart.setProviders(providers);

            if (!formData) {
                multiPart.setMediaType(mediaType);
            }

            for (MIMEPart mp : mm.getAttachments()) {
                BodyPart bodyPart = null;

                if (formData) {
                    bodyPart = new FormDataBodyPart();
                } else {
                    bodyPart = new BodyPart();
                }

                bodyPart.setProviders(providers);

                for (Header h : mp.getAllHeaders()) {
                    bodyPart.getHeaders().add(h.getName(), getFixedHeaderValue(h));
                }

                try {
                    String contentType = bodyPart.getHeaders().getFirst("Content-Type");

                    if (contentType != null) {
                        bodyPart.setMediaType(MediaType.valueOf(contentType));
                    }

                    bodyPart.getContentDisposition();
                } catch (IllegalArgumentException ex) {
                    logger.error( "readFrom error", ex );
                    throw new WebApplicationException(ex, 400);
                }

                bodyPart.setEntity(new BodyPartEntity(mp));
                multiPart.getBodyParts().add(bodyPart);
            }

            if (closeableService != null) {
                closeableService.add(multiPart);
            }

            return multiPart;
        } catch (MIMEParsingException ex) {
            logger.error( "readFrom error", ex );
            throw new WebApplicationException(ex, 400);
        }
    }

}

0
我们遇到了类似的问题,Jetty 突然之间不允许我们上传超过 9194 字节的文件。后来我们发现有人把我们的用户访问权限从 /tmp 中移除了,在某些 Linux 版本中这个目录对应 java.io.tmpdir,因此 Jetty 无法将上传的文件存储在那里,导致出现了 400 错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接