Этот вопрос пару раз задавался на форуме в разные моменты времени, и я пробовал эти решения, но они не работают для меня.Возможно, я использую неправильную комбинацию зависимостей, или они устарели, или другие предоставленные решения не решают мою конкретную проблему.Я не уверен.
Я пытаюсь создать веб-сервис, используя Jersey и Apache для загрузки файла с multipart_form_data, но он вызывает исключение нулевого указателя.Я тестирую, отправляя запрос API с помощью Postman (не устанавливая тип содержимого, а устанавливая тело для данных формы с параметром «Файл» и значением, выбирая файл. Мой файл 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();
}
}
Iя проверяю запрос на почтальоне следующим образом:
POST -> http://localhost:8080/api/download/pdf Тело установлено в опцию «Файл» для данных формы. Выберите Файл, указывающий на действительный файл PDF. Вот код длякак и почтальон.
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--
Ошибка, которую я получаю в почтальоне:
<code><!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)
первопричина
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)
note Полная трассировка стека основной причины доступна в журналах Apache Tomcat / 8.0.15.
Apache Tomcat / 8.0.15