使用@FormDataParam 时 Jersey 不支持媒体类型

Jersey unsupported media type while using @FormDataParam

上传文件的表单 这是一个简单的 html 表单,具有 multipart/form-data enctype。

<pre>
    <form action="api/file/upload" method="post" enctype="multipart/form-data">  
           <p>  
            Select a file : <input type="file" name="file2" size="45" />  
           </p>  
           <input type="submit" value="Upload File" />  
    </form> 
</pre>

这是扩展应用配置rest服务的配置文件

 package org.netbeans.rest.application.config;   
    import java.util.Set;
    import javax.ws.rs.core.Application;
    import org.glassfish.jersey.media.multipart.MultiPartFeature;

    /**
     *
     * @author PRAJIN PRAKASH
     */
    @javax.ws.rs.ApplicationPath("api")
    public class ApplicationConfig extends Application {

        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> resources = new java.util.HashSet<>();
            addRestResourceClasses(resources);
            **resources.add(MultiPartFeature.class);**
//this is added as early post on stack-overflow
            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.mavenproject3.FileUploadeREST.class);
        }

    }

文件上传代码使用@FormDataParam("file") FormDataContentDisposition 和@FormDataParam("file") InputStream uploadedInputStream.

package com.mavenproject3;     

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;


/**
 *
 * @author PRAJIN PRAKASH
 */
@Path("/file")

public class FileUploadeREST {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.TEXT_PLAIN)
    public Response uploadFile(
            @Context ServletContext ctx,
            @FormDataParam("file") InputStream uploadedInputStream
            ,@FormDataParam("file") FormDataContentDisposition filedetails
    ) {
        String root = ctx.getRealPath("/");
        File path = new File(root + "/uploads/");
        if (!path.exists()) {
            boolean status = path.mkdirs();
        }
        String fileLocation = path.getAbsolutePath() + "/" + filedetails.getFileName();
        //saving file  
        try {
            FileOutputStream out = new FileOutputStream(new File(fileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];
            out = new FileOutputStream(new File(fileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String output = "The File successfully uploaded to : " + fileLocation;
        return Response.status(200).entity(output).build();
    }

    @GET
    @Path("/upload")
    public Response getFile() {
        String output = "success";
        return Response.status(200).entity(output).build();
    }

}

本项目的maven依赖

 <?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</groupId>
        <artifactId>mavenproject3</artifactId>
        <version>1.3</version>
        <packaging>war</packaging>

        <name>mavenproject3</name>

        <properties>
            <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

        <dependencies>


            <!-- if you are using Jersey client specific features without the server side -->
            <dependency>
                <groupId>org.glassfish.jersey.media</groupId>
                <artifactId>jersey-media-multipart</artifactId>
                <version>2.25.1</version>
                <type>jar</type>
            </dependency>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-web-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                        <compilerArguments>
                            <endorseddirs>${endorsed.dir}</endorseddirs>
                        </compilerArguments>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.6</version>
                    <executions>
                        <execution>
                            <phase>validate</phase>
                            <goals>
                                <goal>copy</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${endorsed.dir}</outputDirectory>
                                <silent>true</silent>
                                <artifactItems>
                                    <artifactItem>
                                        <groupId>javax</groupId>
                                        <artifactId>javaee-endorsed-api</artifactId>
                                        <version>7.0</version>
                                        <type>jar</type>
                                    </artifactItem>
                                </artifactItems>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>

    </project>

向服务器提交表单时出现空白page.The控制台显示错误 :8080/mavenproject3-1.3/api/file/upload:1 POST http://localhost:8080/mavenproject3-1.3/api/file/upload 415(不支持的媒体类型)

正如 Paul Samsotha 所说,问题出在错误的依赖关系上。 '如果您使用 JBoss/Wildfly,请使用 RESTEasy 的多部分支持。不是泽西岛的。 RESTEasy 是 JBoss/Wildfly'

中的 JAX-RS 实现

我把它改成了resteasy,效果很好

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>2.2.1.GA</version>
</dependency>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-multipart-provider</artifactId>
    <version>2.2.0.GA</version>
</dependency>

<!-- optional, good for handle I/O task -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.0.1</version>
</dependency>

完成教程https://mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/