使用Jersey抛出Null指针异常错误的文件上传API

时间:2019-01-31 02:58:35

标签: java rest jersey jax-rs multipartform-data

这个问题已经在论坛的不同时间问过几次,我已经尝试了这些解决方案,但是它们对我不起作用。也许我使用的依赖关系组合错误,或者它们已经过时,或者提供的不同解决方案不能解决我的特定问题。我不确定。

我正在尝试使用Jersey和Apache创建一个Web服务,以上传带有multipart_form_data的文件,但是它抛出了空指针异常。我通过使用Postman发送API请求进行测试(不是设置内容类型,而是通过选择“文件”选项和值将主体设置为表单数据)。 我的Pom.xml如下:

    <?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.fileupload.ws</groupId>
    <artifactId>testUpload</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>testUpload Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.bundles/jaxrs-ri -->
        <dependency>
            <groupId>org.glassfish.jersey.bundles</groupId>
            <artifactId>jaxrs-ri</artifactId>
            <version>2.28</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-server -->
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.28</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-servlet -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.28</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-common</artifactId>
            <version>2.28</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-multipart -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.28</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>testUpload</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

我的web.xml是

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>jersey.config.server.provider.packages</param-name>
             <param-value>com.testUpload.ws</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>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

修改应用程序代码以添加以下多部分功能:

package com.testUpload.ws;

import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.media.multipart.MultiPartFeature;

/**
 *
 * @author Admin
 */
@ApplicationPath("api")
public class App extends Application {

 @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        resources.add(MultiPartFeature.class);
        addRestResourceClasses(resources);
        return resources;
    }

    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically populated with
     * all resources defined in the project.
     * If required, comment out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(com.testUpload.ws.ui.entrypoint.FileUploadEntryPoint.class);
    }

最后我的入口点代码是:

package com.testUpload.ws.ui.entrypoint;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

/**
 *
 * @author Admin
 */
@Path("/download")
public class FileUploadEntryPoint
{

@POST
@Path("/pdf")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadPdfFile(  @FormDataParam("file") InputStream fileInputStream,
                                @FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
{
    System.out.println("I gt inside");
    if(fileInputStream==null){
    System.out.println("Blank file");    
    }
    String UPLOAD_PATH = "H:/uploaded/";
    try
    {
        int read = 0;
        byte[] bytes = new byte[1024];

        OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName()));
        while ((read = fileInputStream.read(bytes)) != -1)
        {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e)
    {
        throw new WebApplicationException("Error while uploading file. Please try again !!");
    }
    return Response.ok("Data uploaded successfully !!").build();
}   


}

我正在如下测试邮递员的请求:

POST-> http://localhost:8080/api/download/pdf 正文设置为表单数据 “文件”选项。选择“文件”,指向有效的pdf文件。这是与Postman生成的代码相同的代码。

POST /api/download/pdf HTTP/1.1
Host: localhost:8080
cache-control: no-cache
Postman-Token: af7553e5-054a-4ef5-956f-5839efe0c8c1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name=""; filename="C:\Users\Admin\Downloads\abcIBIL.pdf


------WebKitFormBoundary7MA4YWxkTrZu0gW--

我在邮递员中收到的错误是:

<!DOCTYPE html>
<html>
    <head>
        <title>Apache Tomcat/8.0.15 - Error report</title>
        <style type="text/css">H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}.line {height: 1px; background-color: #525D76; border: none;}</style>
    </head>
    <body>
        <h1>HTTP Status 500 - java.lang.NullPointerException</h1>
        <div class="line"></div>
        <p>
            <b>type</b> Exception report
        </p>
        <p>
            <b>message</b>
            <u>java.lang.NullPointerException</u>
        </p>
        <p>
            <b>description</b>
            <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
        </p>
        <p>
            <b>exception</b>
        </p>
        <pre>javax.servlet.ServletException: java.lang.NullPointerException
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:408)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
        <p>
            <b>root cause</b>
        </p>
        <pre>java.lang.NullPointerException
    com.testUpload.ws.ui.entrypoint.FileUploadEntryPoint.uploadPdfFile(FileUploadEntryPoint.java:79)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
    org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    org.glassfish.jersey.internal.Errors.process(Errors.java:244)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:679)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:392)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
        <p>
            <b>note</b>
            <u>The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.</u>
        </p>
        <hr class="line">
        <h3>Apache Tomcat/8.0.15</h3>
    </body>
</html>

0 个答案:

没有答案