java RESTful 生成二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7642258/
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
RESTful produces binary file
提问by Marco Aviles
I'm new using CXF and Spring to make RESTful webservices.
我是使用 CXF 和 Spring 制作 RESTful Web 服务的新手。
This is my problem: I want to create a service that produces "any" kind of file(can be image,document,txt or even pdf), and also a XML. So far I got this code:
这是我的问题:我想创建一个可以生成“任何”类型文件(可以是图像、文档、txt 甚至 pdf)以及 XML 的服务。到目前为止,我得到了这个代码:
@Path("/download/")
@GET
@Produces({"application/*"})
public CustomXML getFile() throws Exception;
I don't know exactly where to begin so please be patient.
我不知道从哪里开始,所以请耐心等待。
EDIT:
编辑:
Complete code of Bryant Luk(thanks!)
Bryant Luk 的完整代码(谢谢!)
@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
if (/* want the pdf file */) {
File file = new File("...");
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; filename =" + file.getName())
.build();
}
/* default to xml file */
return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}
回答by Bryant Luk
If it will return any file, you might want to make your method more "generic" and return a javax.ws.rs.core.Response which you can set the Content-Type header programmatically:
如果它将返回任何文件,您可能希望使您的方法更“通用”并返回一个 javax.ws.rs.core.Response 您可以以编程方式设置 Content-Type 标头:
@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
if (/* want the pdf file */) {
return Response.ok(new File(/*...*/)).type("application/pdf").build();
}
/* default to xml file */
return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}
回答by coolersport
We also use CXF and Spring, and this is my preferable API.
我们也使用 CXF 和 Spring,这是我更喜欢的 API。
import javax.ws.rs.core.Context;
@Path("/")
public interface ContentService
{
@GET
@Path("/download/")
@Produces(MediaType.WILDCARD)
InputStream getFile() throws Exception;
}
@Component
public class ContentServiceImpl implements ContentService
{
@Context
private MessageContext context;
@Override
public InputStream getFile() throws Exception
{
File f;
String contentType;
if (/* want the pdf file */) {
f = new File("...pdf");
contentType = MediaType.APPLICATION_PDF_VALUE;
} else { /* default to xml file */
f = new File("custom.xml");
contentType = MediaType.APPLICATION_XML_VALUE;
}
context.getHttpServletResponse().setContentType(contentType);
context.getHttpServletResponse().setHeader("Content-Disposition", "attachment; filename=" + f.getName());
return new FileInputStream(f);
}
}