2011-10-04 93 views
8

我是新的使用CXF和Spring来制作REST风格的Web服务。RESTful生成二进制文件

这是我的问题:我想创建一个产生“任何”类文件(可以是图像,文档,txt甚至pdf)的服务,也可以是XML。到目前为止,我得到了这样的代码:

@Path("/download/") 
@GET 
@Produces({"application/*"}) 
public CustomXML getFile() throws Exception; 

我不知道从哪里开始,所以请耐心等待。

编辑:科比漉的

完整代码(谢谢!)

@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(); 
} 
+0

试着从解释你的问题开始。到目前为止,你只描述了你已经完成的工作,但是你没有提到代码运行时会发生什么,遇到了什么错误等等。 –

+0

你是否想让框架调用你的'getFile() ''对于'/ download'下的每个请求,所以它可以产生请求的文件?我*想*你在问什么,在这种情况下,'getFile()'的实现是如何找出实际要求的。 – Wyzard

+0

@Wyzard是的,我希望没有太多要求实现和注释类型 –

回答

15

如果它将返回的任何文件,你可能想使你的方法更“通用”,并返回一个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(); 
} 
0

我们还利用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); 
    } 
}