使用jersey-1.7在Google Appengine上上传分段文件

如何解决使用jersey-1.7在Google Appengine上上传分段文件

|| 我在Google Appengine上使用Jersey编写了一个应用程序来处理简单的文件上传。在球衣1.2上使用时效果很好。在更高版本(当前为1.7)中,引入了@FormDataParam来处理多部分/表单输入。我正在使用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创建临时文件?     

解决方法

        对于超出默认大小的文件,ѭ2将创建一个临时文件。为了避免这种情况-在gae上创建文件是不可能的-您可以在项目的resources文件夹中创建一个
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();
}
    ,        为了使那些在Eclipse和GPE(Eclipse的Google插件)结合使用时苦苦挣扎的人受益,我给出了这个略微修改的解决方案,该解决方案源自@yves \'的答案。 我已经用
App Engine SDK 1.9.10
Jersey 2.12
测试过。由于其他问题,8等不适用于ѭ8work。 在
\\war\\WEB-INF\\classes
文件夹下,创建一个名为
jersey-multipart-config.properties
的新文件。编辑文件,使其包含行“ 11”。 请注意,“ 12”文件夹在Eclipse中是隐藏的,因此请在操作系统的文件浏览器(例如Windows资源管理器)中查找该文件夹。 现在,无论是在初始化“ 2”功能(在Jersey servlet初始化时)还是在完成文件上传(在Jersey servlet发布请求时),临时文件都将不再创建,并且GAE不会抱怨。     ,        将文件
jersey-multipart-config.properties
放在WAR中的
WEB-INF/classes
下非常重要。 通常在WAR文件结构中,将配置文件(
web.xml
appengine-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>
您的项目结构如下所示: 泽西岛2.x中
jersey-multipart-config.properties
的内容:
jersey.config.multipart.bufferThreshold = -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,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);
        }
    }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-