java JAX-RS 接受图像作为输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14858321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:38:46  来源:igfitidea点击:

JAX-RS Accept Images as input

javaweb-servicesrestjax-rs

提问by Brams

For quite some time now, I've been developing JAX-RS web services for my development needs. All the methods that I've written so far accept java Strings or primitive types as input.

一段时间以来,我一直在开发 JAX-RS Web 服务以满足我的开发需求。到目前为止,我编写的所有方法都接受 java 字符串或原始类型作为输入。

An example of such a method:

这种方法的一个例子:

@POST  
@Path("MyMethod")  
@Produces(MediaType.APPLICATION_JSON)  
public String MyMethod(@FormParam("username")String username, @FormParam("password")String passowrd)

What I'm trying to do now is accept images as input. I read a lot of articles regarding this. Some suggested accepting the base64 encoding as input and others suggested accepting an actual InputSteam.

我现在要做的是接受图像作为输入。我阅读了很多关于这方面的文章。有些人建议接受 base64 编码作为输入,而其他人则建议接受实际的 InputSteam。

However, i'm yet to see a full blown example on how to accept an InputStream. I read about the @consumer annotation and @Provider but i still can't wrap my head around it. Is there an article, documentation or an example that somehow guides me toward this? i.e. A step by step process on how to implement rather than displaying theory.

但是,我还没有看到有关如何接受 InputStream 的完整示例。我阅读了@consumer 注释和@Provider,但我仍然无法理解它。是否有文章、文档或示例以某种方式指导我进行此操作?即关于如何实施而不是展示理论的逐步过程。

I know that the base64 encoding works but out of curiosity i would like to know how the other approach works as well...Thanks in advance.

我知道 base64 编码有效,但出于好奇,我想知道其他方法也是如何工作的......提前致谢。

采纳答案by yegor256

This should work:

这应该有效:

import org.apache.commons.io.IOUtils;
@POST
@Path("MyMethod") 
@Consumes("*/*") // to accept all input types 
public String MyMethod(InputStream stream) {
    byte[] image = IOUtils.toByteArray(stream);
    return "done";
}

回答by Torsten R?mer

Probably not the preferred but a simple way to combine InputStreamwith one or more path parameters:

可能不是首选,而是一种InputStream与一个或多个路径参数结合的简单方法:

@POST
@Path("page/{page}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces("image/jpeg")
public StreamingOutput generatePage(final InputStream inputStream, @Context UriInfo uriInfo) {
    final int page = Integer.parseInt(uriInfo.getPathParameters().getFirst("page"));
    return (outputStream) -> {
        service.generatePage(page, inputStream, outputStream);
    };
}