Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用jersey-1.7在Google Appengine上上传多部分文件_Java_Google App Engine_Jersey - Fatal编程技术网

Java 使用jersey-1.7在Google Appengine上上传多部分文件

Java 使用jersey-1.7在Google Appengine上上传多部分文件,java,google-app-engine,jersey,Java,Google App Engine,Jersey,我用Jersey在Google Appengine上编写了一个应用程序来处理简单的文件上传。当它在泽西1.2上运行时,效果很好。在更高版本(当前1.7)中,引入@FormDataParam来处理多部分/表单输入。我正在使用jersey multipart和mimepull依赖项。似乎新的做法是在appengine中创建临时文件,我们都知道这是非法的 我是不是错过了什么或者做错了什么,因为泽西现在应该和阿彭金兼容了 @POST @Path("upload") @Consumes(MediaTy

我用Jersey在Google Appengine上编写了一个应用程序来处理简单的文件上传。当它在泽西1.2上运行时,效果很好。在更高版本(当前1.7)中,引入@FormDataParam来处理多部分/表单输入。我正在使用jersey multipart和mimepull依赖项。似乎新的做法是在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创建临时文件?

对于超出默认大小的文件,
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();
}

我找到了一个解决方案,可以通过编程避免使用临时文件创建(对于GAE实现非常有用)

我的解决方案包括创建一个新的MultiPartReader提供程序。。。在我的代码下面


@Provider
@使用(“多部分/*”)
公共类GaeMultiPartReader实现MessageBodyReader{
最终日志记录器=org.apache.commons.logging.LogFactory.getLog(getClass());
私人最终提供者;
私人最终可关闭服务可关闭服务;
私有最终MIMEConfig MIMEConfig;
私有字符串getFixedHeaderValue(标题h){
字符串结果=h.getValue();
if(h.getName().equals(“内容处置”)&&(result.indexOf(“filename=”)!=-1)){
试一试{
结果=新字符串(result.getBytes(),“utf8”);
}捕获(不支持的编码异常e){
最后一个字符串msg=“无法将标题\“内容处置\”转换为UTF8格式。”;
记录器错误(msg,e);
抛出新的运行时异常(msg);
}
}
返回结果;
}
public GaeMultiPartReader(@Context-Providers-Providers,@Context-MultiPartConfig-config,
@上下文可关闭服务(可关闭服务){
这个。提供者=提供者;
if(config==null){
final String msg=“我们期望的MultiPartConfig实例不存在。”
+“您是否已注册MultiPartConfigProvider类?”;
记录器错误(msg);
抛出新的IllegalArgumentException(msg);
}
this.closeableService=closeableService;
mimeConfig=新的mimeConfig();
//setMemoryThreshold(config.getBufferThreshold());
mimeConfig.setMemoryThreshold(-1L);//GAE FIX
}
@凌驾
公共布尔值可读取(类类型、类型genericType、注释[]注释、MediaType MediaType){
返回MultiPart.class.isAssignableFrom(类型);
}
@凌驾
公共多部分读取自(类类型、类型genericType、批注[]批注、MediaType MediaType、,
多值映射头、InputStream流)引发IOException、WebApplicationException{
试一试{
mimessage mm=新的mimessage(stream,mediaType.getParameters().get(“边界”),mimeConfig);
布尔formData=false;
MultiPart MultiPart=null;
if(MediaTypes.typeEquals(mediaType,mediaType.MULTIPART\u FORM\u DATA\u TYPE)){
multiPart=new FormDataMultiPart();
formData=true;
}否则{
multiPart=新的multiPart();
}
多部分设置提供程序(提供程序);
如果(!formData){
multiPart.setMediaType(mediaType);
}
对于(MIMEPart mp:mm.getAttachments()){
BodyPart BodyPart=null;
if(formData){
bodyPart=新FormDataCodePart();
}否则{
车身部件=新车身部件();
}
bodyPart.setProviders(提供者);
for(标头h:mp.getAllHeaders()){
添加(h.getName(),getFixedHeaderValue(h));
}
试一试{
字符串contentType=bodyPart.getHeaders().getFirst(“内容类型”);
if(contentType!=null){
bodyPart.setMediaType(MediaType.valueOf(contentType));
}
getContentDisposition();
}捕获(IllegalArgumentException ex){
logger.error(“读取错误”,ex);
抛出新的WebApplicationException(例如,400);
}
bodyPart.setEntity(新BodyPartEntity(mp));
multiPart.getBodyParts().add(bodyPart);
}
if(closeableService!=null){
closeableService.add(多部分);
}
返回多部分;
}捕获(MIMEParsingException ex){
logger.error(“读取错误”,ex);
抛出新的WebApplicationException(例如,400);
}
}
}

我们遇到了一个类似的问题,Jetty不允许我们上传超过9194字节的文件(突然—有一天),后来我们意识到有人从/tmp获取了我们的用户访问权限,在某些linux版本上,它对应于java.io.tmpdir,因此Jetty无法将上传的文件存储在那里,我们得到了一个400错误。

为了让那些在使用Eclipse和GPE(Google插件For Eclipse)时遇到困难的人受益,我给出了这个从@yves的答案派生出来的稍加修改的解决方案

我已经用appenginesdk1.9.10和Jersey 2.12对它进行了测试它不适用于
应用程序引擎SDK 1.9.6->1.9.9
  @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);
        }
    }

}
        <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.config.multipart.bufferThreshold = -1