Jersey 2.x 开发 restful 服务中,文件上传报错:
[2018-04-26 11:24:51,540] Artifact XHbase:war exploded: Artifact is deployed successfully
[2018-04-26 11:24:51,540] Artifact XHbase:war exploded: Deploy took 5,718 milliseconds
26-Apr-2018 11:25:04.912 严重 [http-nio-8413-exec-24] org.glassfish.jersey.internal.Errors.logErrors Following issues have been detected:
WARNING: No injection source found for a parameter of type public void com.xcar.rest.resources.xcar_pic.PictureResource.put(java.lang.String,java.lang.String,java.lang.String) throws java.io.IOException at index 1.
代码如下:
@Path("/v1/pictures/")
public class PictureResource {
@POST @Path("/{param}")
@Consumes(MediaType.MULTIPART_FORM_DATA) //MediaType.APPLICATION_OCTET_STREAM,MediaType.APPLICATION_FORM_URLENCODED,
public void put(@PathParam("param") String pic_name,
@FormDataParam("key1") String value1,
@FormDataParam("key2") String value2) throws IOException {
System.out.println(pic_name);
System.out.println(value1);
System.out.println(value2);
}
}
客户端截图如下:
pom 文件依赖如下:
<!--jersey 2.x-->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
明明引用了 jersey-media-multipart 模块,为什么还是报错呢?
原来少了一个步骤,如下:
public class MyRestApplication extends ResourceConfig {
public MyRestApplication() {
//服务类所在的包路径
packages("com.xcar.rest.resources");
//注册JSON转换器
register(JacksonJsonProvider.class);
//注册文件上传模块
register(MultiPartFeature.class);
}
}
注意:一定要在这里进行注册才可以注入成功的!!!!
搞定!
参考文献:
1. MULTIPART_FORM_DATA: No injection source found for a parameter of type public javax.ws.rs.core.Response