MULTIPART_FORM_DATA:找不到类型为 public javax.ws.rs.core.Response 的参数的注入源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30653012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MULTIPART_FORM_DATA: No injection source found for a parameter of type public javax.ws.rs.core.Response
提问by Swarup Saha
I am using Jersey based restful Service implementation strategy to build a service which will be used to upload files. My service class name is : UploadFileService.java (See Code below)
我正在使用基于 Jersey 的 restful 服务实现策略来构建一个将用于上传文件的服务。我的服务类名称是:UploadFileService.java(见下面的代码)
package com.jerser.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
@Path("/fileUpload")
public class UploadFileService {
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
These are the JAR files I have inside my lib:
这些是我的库中的 JAR 文件:
aopalliance-repackaged-2.4.0-b10.jar asm-debug-all-5.0.2.jar hk2-api-2.4.0-b10.jar hk2-locator-2.4.0-b10.jar hk2-utils-2.4.0-b10.jar javassist-3.18.1-GA.jar javax.annotation-api-1.2.jar javax.inject-2.4.0-b10.jar javax.servlet-api-3.0.1.jar javax.ws.rs-api-2.0.1.jar jaxb-api-2.2.7.jar jersey-client.jar jersey-common.jar jersey-container-servlet-core.jar jersey-container-servlet.jar jersey-core-1.11.jar jersey-guava-2.17.jar jersey-media-jaxb.jar jersey-multipart-1.18.jar jersey-server.jar org.osgi.core-4.2.0.jar osgi-resource-locator-1.0.1.jar persistence-api-1.0.jar validation-api-1.1.0.Final.jar
aopalliance-repackaged-2.4.0-b10.jar asm-debug-all-5.0.2.jar hk2-api-2.4.0-b10.jar hk2-locator-2.4.0-b10.jar hk2-utils-2.4.0-b10.jar javassist-3.18.1-GA.jar javax.annotation-api-1.2.jar javax.inject-2.4.0-b10.jar javax.servlet-api-3.0.1.jar javax.ws.rs-api-2.0.1.jar jaxb-api-2.2.7.jar jersey-client.jar jersey-common.jar jersey-container-servlet-core.jar jersey-container-servlet.jar jersey-core-1.11.jar jersey-guava-2.17.jar jersey-media-jaxb.jar jersey-multipart-1.18.jar jersey-server.jar org.osgi.core-4.2.0.jar osgi-resource-locator-1.0.1.jar persistence-api-1.0.jar validation-api-1.1.0.Final.jar
I am getting the following error when I am trying to up my tomcat server :
当我尝试启动我的 tomcat 服务器时出现以下错误:
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response com.jerser.service.UploadFileService.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[multipart/form-data], producedTypes=[], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.jerser.service.UploadFileService, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@d3e2d4]}, definitionMethod=public javax.ws.rs.core.Response com.jerser.service.UploadFileService.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition), parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null], Parameter [type=class com.sun.jersey.core.header.FormDataContentDisposition, source=file, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}']
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:528)
at org.glassfish.jersey.server.ApplicationHandler.access0(ApplicationHandler.java:166)
at org.glassfish.jersey.server.ApplicationHandler.run(ApplicationHandler.java:327)
at org.glassfish.jersey.internal.Errors.call(Errors.java:289)
at org.glassfish.jersey.internal.Errors.call(Errors.java:286)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:324)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:338)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:171)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:363)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1176)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1102)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1009)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4885)
at org.apache.catalina.core.StandardContext.call(StandardContext.java:5212)
at org.apache.catalina.core.StandardContext.call(StandardContext.java:5207)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Over the internet I found there are plenty of example which shows How to upload MULTIPART file using RESTFul API. But with same solution. I am not able to run those code as well. I think I am doing something wrong with the JAR files. Could anyone please help me on this?
在互联网上,我发现有很多示例展示了如何使用 RESTFul API 上传 MULTIPART 文件。但使用相同的解决方案。我也无法运行这些代码。我想我对 JAR 文件做错了。任何人都可以帮我解决这个问题吗?
采纳答案by Paul Samsotha
Get rid of jersey-multipart-1.18.jar
. That is for Jersey 1.x. Add these two
摆脱jersey-multipart-1.18.jar
. 这适用于 Jersey 1.x。添加这两个
For Maven you would use the following dependency (you don't need to explicitly add the mimepull
dependency, as this one will pull it in).
对于 Maven,您将使用以下依赖项(您不需要显式添加mimepull
依赖项,因为这会将其拉入)。
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.17</version> <!-- Make sure the Jersey version matches
the one you are currently using -->
</dependency>
Then you need to register the MultiPartFeature
. If you are using a ResourceConfig
for configuration, you can simply do
然后你需要注册MultiPartFeature
. 如果您使用的是ResourceConfig
for 配置,则可以简单地执行
register(MultiPartFeature.class);
If you are using web.xml, then you can add the class as an <init-param>
to the Jersey servlet
如果您使用的是 web.xml,那么您可以将该类作为 an 添加<init-param>
到 Jersey servlet
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
Note that if you have multiple providers that you want to register, then you can delimit each provider class with a comma or semicolon. You cannot use this same param-name
twice. See Suarabh's answer
请注意,如果您有多个要注册的提供程序,则可以使用逗号或分号分隔每个提供程序类。您不能param-name
两次使用相同的内容。见Suarabh 的回答
UPDATE
更新
Also, once you get rid of jersey-multipart-1.18.jar
you will have compile errors for the missing imported classes. For the most part, the class names are still the same, just the packages have changed, i.e.
此外,一旦您摆脱jersey-multipart-1.18.jar
了丢失的导入类,您将遇到编译错误。大多数情况下,类名仍然相同,只是包发生了变化,即
org.glassfish.jersey.media.multipart.FormDataParam
org.glassfish.jersey.media.multipart.FormDataContentDisposition
org.glassfish.jersey.media.multipart.FormDataParam
org.glassfish.jersey.media.multipart.FormDataContentDisposition
For Dropwizard
对于 Dropwizard
If you're using Dropwizard, instead of adding the jersey-media-multipart
, they document for your to add dropwizard-forms
instead. And instead of registering the MultiPartFeature
, you should register the MultiPartBundle
如果您使用 Dropwizard,而不是添加jersey-media-multipart
,它们会记录供您添加dropwizard-forms
。而不是注册MultiPartFeature
,您应该注册MultiPartBundle
@Override
public void initialize(Bootstrap<ExampleConfiguration> bootstrap) {
bootstrap.addBundle(new MultiPartBundle());
}
Really doesn't make much difference though as all the Dropwizard bundle does is register the MultiPartFeature
with the ResourceConfig.
尽管 Dropwizard 捆绑包所做的只是MultiPartFeature
向 ResourceConfig注册,但实际上并没有太大区别。
Aside
在旁边
If you are here for a different ModelValidationException
, here are some links for information on other causes of the exception.
如果您是为了不同的ModelValidationException
,这里有一些链接,可提供有关其他异常原因的信息。
回答by Saurabh
I too got the same exception.I did the following changes in web.xml
我也有同样的异常。我在 web.xml 中做了以下更改
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.moxy.json.MoxyFeature;org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
and changed jersey 2.7 to 2.9 .I do not know what change of this 2 has solved the issue.
并将球衣 2.7 更改为 2.9。我不知道这 2 的更改解决了问题。
回答by Anant Simran Singh
If someone is using @FormDataParam
with @ApiOperation
swagger annotation, it won't work(as per swagger latest version at this time) as mentioned here:
如果有人使用@FormDataParam
与@ApiOperation
招摇的注解,它不会工作(此时为每招摇最新版本)这里所说:
回答by RoutesMaps.com
Register MultiPartFeature. In web.xml add to the Jersey servlet:
注册 MultiPartFeature。在 web.xml 中添加到 Jersey servlet:
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
回答by markgp
I had this same problem with Scala and this helped me solve it. Just want to add some Scala specific details to help anyone using Dropwizard with Scala. Here is an example of how to "register" the MultiPartFeature in a Scala and Dropwizard project.
我在 Scala 上遇到了同样的问题,这帮助我解决了它。只是想添加一些 Scala 特定的细节来帮助任何人使用 Dropwizard 和 Scala。以下是如何在 Scala 和 Dropwizard 项目中“注册” MultiPartFeature 的示例。
package org.research.s3.service
import io.dropwizard.Application
import io.dropwizard.setup.Environment
import org.research.s3.service.resource._
import org.research.service.s3.resource.UploadResource
import org.glassfish.jersey.media.multipart.{FormDataParam,MultiPartFeature}
class CmdaaApp() extends Application[CmdaaAppConfig] {
override def run(t: CmdaaAppConfig, env: Environment): Unit = {
env.jersey().register(new RootResource)
//Need this to make the file upload code work in
env.jersey().register(new MultiPartFeature)
env.jersey().register(new UploadResource(curBucket))
}
}
object CmdaaApp {
def main(args: Array[String]): Unit = new CmdaaApp().run(args: _*)
}
and here is the code for the UploadResource that does the upload:
这是执行上传的 UploadResource 的代码:
package org.research.service.s3.resource
import java.io.{FileInputStream, InputStream}
import com.google.gson.{Gson, GsonBuilder}
import javax.ws.rs.core.MediaType.APPLICATION_JSON
import javax.ws.rs._
import javax.ws.rs.core.Response
import javax.ws.rs.core.MediaType
import org.research.util.OptionSerializer
import org.research.s3.service.resource.s3Bucket
import org.glassfish.jersey.media.multipart.{FormDataParam,MultiPartFeature}
@Path("/file")
class UploadResource(currentBucket: s3Bucket) {
val gsonb = new GsonBuilder()
gsonb.registerTypeAdapter(classOf[Option[Any]], new OptionSerializer)
val gson = gsonb.create
@POST
@Path("upload")
@Produces(Array(APPLICATION_JSON))
@Consumes(Array(MediaType.MULTIPART_FORM_DATA))
// def uploadFile(): Response = {
def uploadFile(@FormDataParam("file") uploadedInputStream: InputStream): Response = {
/* Need code here to get a uuid for the file name
Then return the uuid if we have success and of course 200
*/
Response.ok.entity(currentBucket.upload("testName",uploadedInputStream,false)).build()
//Response.ok().build()
}
}
This code refers to an s3 bucket but you don't need that. You can just replace that call with code do download your incoming file data to a regular file. scala
此代码指的是 s3 存储桶,但您不需要它。您可以只用代码替换该调用,将传入的文件数据下载到常规文件中。 斯卡拉
回答by Ahmad Abdelghany
Yet another possible cause for this very generic error is that Jersey only searches for factories associated with the last annotation when multiple ones are declared on a param. (See bug report)
这个非常普遍的错误的另一个可能原因是,当在一个参数上声明了多个工厂时,Jersey 只搜索与最后一个注释关联的工厂。(见错误报告)
Until this is fixed, if you are using any other annotations besides @FormDataParam
, it has to come last.
在修复此问题之前,如果您正在使用除 之外的任何其他注释@FormDataParam
,则它必须放在最后。
This works:
这有效:
@NotEmpty @FormDataParam("myParam") String myParam
This does not:
这不会:
@FormDataParam("myParam") @NotEmpty String myParam
回答by Alexander Yushko
I had the same problem when I tried to upload the file. I spent a lot of time until I found a solution to the problem.
当我尝试上传文件时遇到了同样的问题。我花了很多时间才找到解决问题的方法。
1.If you changed version of your JARs files you may have a version conflicts!
1.如果您更改了 JAR 文件的版本,您可能会遇到版本冲突!
Clean up your artifacts/libs and rebuild project.
清理您的工件/库并重建项目。
2.You need to register your UploadFileService class too:
2.您还需要注册您的 UploadFileService 类:
register(MultiPartFeature.class);
register(UploadFileService.class);
Hope it will help someone and save your time.
希望它会帮助某人并节省您的时间。