415上载文件时,java rest服务上的媒体类型不受支持

时间:2018-05-18 18:21:45

标签: rest jersey jax-rs

我正在尝试构建一个上传文件的休息服务。这就是我所拥有的。当我在邮递员中测试时,我选择了表单数据,并将“文件”设置为我正在上传的文件。

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@RequestParam("file") MultipartFile file)

我的理解是我需要jersey-media-multipart依赖

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

当我尝试发布帖子请求时,我收到415不支持的媒体类型错误,我不确定原因。它被设置为使用MULTIPART_FORM_DATA,参数是MultipartFile。

编辑我添加了如下配置,

@Configuration
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        register(MultiPartFeature.class);
    }
}

我还修复了我的资源

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(
        @FormDataParam("file") InputStream file,
        @FormDataParam("file") FormDataContentDisposition fdcd,
        @FormDataParam("file-detail") String fileDetail) throws IOException {

现在我得到[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response

这是我的spring引导类,其中包含其他配置

    @SpringBootApplication
@EnableCircuitBreaker
@EntityScan("com.whatever.")
@ImportResource({"classpath*:/META-INF/**/spring-bootstrap.xml"})
@Import({JerseyConfig.class})
@EnableJpaRepositories(basePackages="whatever", entityManagerFactoryRef="entityManagerFactory")
public class Application {

protected TomcatEmbeddedServletContainerFactory createTomcatEmbeddedServletContainerFactory() {
        return new TomcatEmbeddedServletContainerFactory() {

            @Override
            protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
                ((StandardHost) tomcat.getHost()).setErrorReportValveClass(StringUtils.EMPTY);
                return super.getTomcatEmbeddedServletContainer(tomcat);
            }
        };
    }

    @Bean
    public FilterRegistrationBean requestContextFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean(new org.springframework.web.filter.RequestContextFilter());
        filterRegistration.setName("RequestContextFilter");
        filterRegistration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        filterRegistration.addUrlPatterns(BASE_PATH + "*");
        return filterRegistration;
    }    

    @Bean 
    public FilterRegistrationBean springSecurityFilterChain() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean(new org.springframework.web.filter.DelegatingFilterProxy());
        filterRegistration.setName("SpringSecurityFilterChain");
        filterRegistration.setOrder(Ordered.HIGHEST_PRECEDENCE + 2);
        filterRegistration.addUrlPatterns(BASE_PATH + "*");
        return filterRegistration;
    }

    @Bean
    @Conditional(NonWindowsCondition.class)
    public FilterRegistrationBean f5Filter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean(new F5Filter());
        filterRegistration.setName("F5Filter");
        filterRegistration.setOrder(Ordered.HIGHEST_PRECEDENCE + 3);
        filterRegistration.addUrlPatterns(BASE_PATH + "*");
        return filterRegistration;
    }  

    /**
     * Initializes and registers the JAX-RS filter implementation, currently Jersey.
     * 
     * @return The JAX-RS filter registration.
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    @Bean
    public FilterRegistrationBean jaxrsFilter() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        Filter filter = (Filter) Class.forName("org.glassfish.jersey.servlet.ServletContainer").newInstance();
        jerseyFilterRegistration.setFilter(filter);
        jerseyFilterRegistration.setName("JerseyFilter");
        jerseyFilterRegistration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
        // Set the Jersey filter mapping and context path
        jerseyFilterRegistration.addUrlPatterns(BASE_PATH + "*");
        jerseyFilterRegistration.addInitParameter("jersey.config.servlet.filter.contextPath", BASE_PATH);
        // Load the common package and application package
        jerseyFilterRegistration.addInitParameter("jersey.config.server.provider.packages", "com.whatever.jaxrs.feature;com.whatever.fig.risk.webservice.resource");
        // Enable media type mappings on the URI such as .xml and .json
        jerseyFilterRegistration.addInitParameter("jersey.config.server.mediaTypeMappings", "xml:application/xml, json:application/json");
        // Enable Java bean validation integration
        jerseyFilterRegistration.addInitParameter("jersey.config.beanValidation.enableOutputValidationErrorEntity.servers", "true");
        // Disable the application.wadl from being generated and publicly visible (ITSO finding)
        jerseyFilterRegistration.addInitParameter("jersey.config.server.wadl.disableWadl", "true");        
        // Forward 404s to Spring MVC, which serves up the Actuator endpoints and non-jersey resources 
        jerseyFilterRegistration.addInitParameter("jersey.config.servlet.filter.forwardOn404", "true");

        if (isJerseyDebug) {
            // Debug parameter switches
            jerseyFilterRegistration.addInitParameter("jersey.config.server.monitoring.statistics.enabled", "true");
            jerseyFilterRegistration.addInitParameter("jersey.config.server.tracing.type", "ALL");
            jerseyFilterRegistration.addInitParameter("jersey.config.server.tracing.threshold", "VERBOSE");
        }

        return jerseyFilterRegistration;
    }

1 个答案:

答案 0 :(得分:1)

@RequestParamMultipartFile都属于Spring而不是Jersey。对于Jersey,您要使用的是注释@FormDataParam,对于参数,根据零件类型,您可以使用许多不同类型的参数。如果部件是文件,则可以使用InputStreamFilebyte[]参数,或者如果部件是纯文本,则可以使用String参数。如果您需要文件名,则可以添加 FormDataContentDisposition参数以及零件实体参数。以下是一个例子

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(
        @FormDataParam("file") InputStream file,
        @FormDataParam("file") FormDataContentDisposition fdcd,
        @FormDataParam("file-detail") String fileDetail) {

}

要完成这项工作,您需要在应用程序中注册MultiPartFeature。您可以通过this post查看注册方式。

另见: