在Spring Boot中使用Jersey进行文件上传,获得400 Bad Request

时间:2018-04-20 16:01:23

标签: spring-boot jersey

我已尝试过大量使用jersey进行文件上传的示例。我可以使用@RequestMapping,ResponseEntity而不是@Path来使用纯Spring。但是我想使用jersey,因为我的所有其他端点都是由泽西处理的。

更新:我觉得我无法传递表单数据,文件或文本。即使是@FormDataParam("directory") String directory的单个FormDataParam也会提供错误的请求

我有以下课程

@Component
@Path("/v1.0")
public class FileOperationsResource  {

    private ConfigurationReader mConfigReader;

    @Autowired
    public FileOperationsResource(ConfigurationReader configurationReader) {
        mConfigReader = configurationReader;
    }

   @POST
   @Path("/file/upload")
   @Consumes(MediaType.MULTIPART_FORM_DATA)
   public Response uploadFile(@QueryParam("dir") String directory,
                              @FormDataParam("file") InputStream file,
                              @FormDataParam("file") FormDataContentDisposition fileDisposition) {

我已将以下行添加到我的ResourceConfig

register(MultiPartFeature.class);

我添加了以下maven依赖项,但是没有添加版本,因为我的理解是它会自动提取适用于我的spring版本的版本,并且我发现更新的版本不再允许我添加注册ResourceConfig MultiPartFeature缺少<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-multipart</artifactId> </dependency>

{
    "timestamp": "2018-04-20T15:51:01.790+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Bad Request",
    "path": "/api/v1.0/file/upload"
}

当我拨打以下电话时,收到400 Bad Request。我觉得我必须把电话弄错,或者没有连接其他东西。任何帮助都会受到赞赏。

响应:

curl --verbose --form file=@"settings.xml" http://localhost:8080/api/v1.0/file/upload?dir=MyDir

我已经使用Postman和使用表单进行了通话,并且通过以下调用进行了卷曲

brew install mysql

1 个答案:

答案 0 :(得分:1)

spring.jersey.type设置的application.properties是什么?我有使用Jersey和Boot的文件上传工作,我相信这就是你需要的:

# JERSEY
spring.jersey.type=servlet
spring.jersey.servlet.load-on-startup=1

例如,这是我的终点:

@POST
@Path("/file/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream,
                           @FormDataParam("file") FormDataContentDisposition fileDisposition) {

    String fileName = fileDisposition.getFileName();
    StringBuilder fileContents = new StringBuilder();
    int read = 0;
    int totalBytesRead = 0;
    byte[] bytes = new byte[1024];
    try {
        while ((read = fileInputStream.read(bytes)) != -1) {
            ...save file...
        }
    } catch (IOException e) {
        mLogger.error(e.getMessage(), e);
    }

    return Response.ok().build();
}
相关问题