簡體   English   中英

MULTIPART_FORM_DATA:沒有為公共 javax.ws.rs.core.Response 類型的參數找到注入源

[英]MULTIPART_FORM_DATA: No injection source found for a parameter of type public javax.ws.rs.core.Response

我正在使用基於 Jersey 的 restful 服務實現策略來構建一個用於上傳文件的服務。 我的服務 class 名稱是: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();
        }

    }

}

這些是我的庫中的 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

當我嘗試升級我的 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.access$500(ApplicationHandler.java:166)
    at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:327)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
    at org.glassfish.jersey.internal.Errors$2.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$3.call(StandardContext.java:5212)
    at org.apache.catalina.core.StandardContext$3.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)

在互聯網上,我發現有很多示例顯示如何使用 RESTFul API 上傳 MULTIPART 文件。 但使用相同的解決方案。 我也無法運行這些代碼。 我想我對 JAR 文件做錯了。 有人可以幫我嗎?

擺脫jersey-multipart-1.18.jar 這適用於 Jersey 1.x。 添加這兩個

對於 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>

然后你需要注冊MultiPartFeature 如果您使用ResourceConfig進行配置,則只需執行

register(MultiPartFeature.class);

如果您使用的是 web.xml,那么您可以將該類作為<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>

請注意,如果您有多個要注冊的提供程序,則可以使用逗號、分號或空格/換行符分隔每個提供程序類。 您不能兩次使用相同的param-name Suarabh 的回答

更新

此外,一旦您擺脫了jersey-multipart-1.18.jar您將jersey-multipart-1.18.jar缺少的導入類的編譯錯誤。 大多數情況下,類名仍然相同,只是包發生了變化,即


對於 Dropwizard

如果您使用 Dropwizard,而不是添加jersey-media-multipart ,他們會記錄您添加dropwizard-forms 而不是注冊MultiPartFeature ,你應該注冊MultiPartBundle

@Override
public void initialize(Bootstrap<ExampleConfiguration> bootstrap) {
    bootstrap.addBundle(new MultiPartBundle());
}

盡管 Dropwizard 包所做的只是將MultiPartFeature注冊到ResourceConfig但實際上並沒有太大區別。


在旁邊

如果您在這里遇到不同的ModelValidationException ,這里有一些鏈接,可提供有關其他異常原因的信息。

這個非常普遍的錯誤的另一個可能原因是,當在一個參數上聲明多個工廠時,Jersey 僅搜索與最后一個注釋關聯的工廠。 (見錯誤報告

在修復此問題之前,如果您使用除@FormDataParam之外的任何其他注釋,則它必須@FormDataParam最后。

這有效:

@NotEmpty @FormDataParam("myParam") String myParam

這不會:

@FormDataParam("myParam") @NotEmpty String myParam

我也有同樣的異常。我在 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>

並將球衣 2.7 更改為 2.9。我不知道這 2 的更改解決了問題。

注冊 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>

下面的代碼對我有用:

類 ->>> 添加它

類屬性 --->> 添加它


公共類 userREST() {

@POST
    @Path("upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public Response uploadImageFile(@FormDataParam("uploadFile") InputStream fileInputStream,
            @FormDataParam("uploadFile") FormDataContentDisposition fileFormDataContentDisposition,
            @FormDataParam("FIR_REG_NUM") String FIR_REG_NUM, @FormDataParam("LOGIN_ID") String LOGIN_ID) {

        final_json_result = WriteFileInFolder.fileAnalysis(fileInputStream, fileFormDataContentDisposition, FIR_REG_NUM,
                LOGIN_ID);

        return Response.ok(final_json_result).build();

    }// uploadImageFile

公共類文件JAXRSConfig(){

package ####.jaxrs.jwt;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import ####.helper.Common@@@;
import ####.jaxrs.jwt.filters.JWTRequestFilter;
import ####.jaxrs.jwt.filters.JWTResponseFilter;
import ####.service.FileServicesREST;



@ApplicationPath("fileservice")
public class FileJAXRSConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {

        Common@@@.logging("@ApplicationPath@FileServicesREST...");
        Set<Class<?>> clazzes = new HashSet<Class<?>>();
        clazzes.add(JWTRequestFilter.class);
        clazzes.add(FileServicesREST.class);
        clazzes.add(JWTResponseFilter.class);

        return clazzes;
    }


    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("jersey.config.server.provider.packages", "####.service");
        properties.put("jersey.config.server.provider.classnames", "org.glassfish.jersey.media.multipart.MultiPartFeature");
        return properties;
    }

}

不需要在 web.xml 中添加以下內容

<init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>mha.@@@.service</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>

如果有人將@FormDataParam@ApiOperation swagger 注釋一起使用,它將不起作用(根據此時的 swagger 最新版本),如下所述:

https://github.com/swagger-api/swagger-ui/issues/169

我在 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: _*)
}

這是執行上傳的 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()
  }

}

此代碼指的是 s3 存儲桶,但您不需要它。 您可以只用代碼替換該調用,將傳入的文件數據下載到常規文件中。

當我嘗試上傳文件時遇到了同樣的問題。 我花了很多時間才找到解決問題的方法。

1.如果您更改了 JAR 文件的版本,您可能會遇到版本沖突!

清理您的工件/庫並重建項目。

2.您還需要注冊您的 UploadFileService 類:

register(MultiPartFeature.class);
register(UploadFileService.class);

希望它會幫助某人並節省您的時間。

以防將來有人遇到這個問題並遇到我遇到的同樣問題。 確保您導入的注釋來自正確的包。 異常不會告訴您哪個參數有問題,它可能是任何一個參數。 就我而言,我導入的是javax.websocket.server.PathParam而不是javax.ws.rs.PathParam

如果您在為上傳資源編寫 Dropwizard 測試時遇到此錯誤,這是解決方案:

  1. 添加對 dropwizard-forms 的依賴

2.在應用程序文件中添加:

    @Override
    public void initialize(Bootstrap<ExampleConfiguration> bootstrap) {
        bootstrap.addBundle(new MultiPartBundle());
    }
  1. 在測試文件中添加:
    ResourceExtension.builder()
                .addResource(new FileResource())
                .addProvider(new MultiPartFeature())
                .build();

我有一個非常相似的問題,幫助我的答案是這個https://stackoverflow.com/a/30407999/6801721

我試圖使用用戶定義的 object 作為查詢參數,並且除非滿足某些條件,否則通常不允許使用答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM