2011-10-04 23 views
8

Soy nuevo usando CXF y Spring para hacer RESTful webservices.RESTful produce el archivo binario

Este es mi problema: quiero crear un servicio que produzca "cualquier" tipo de archivo (puede ser imagen, documento, txt o incluso pdf), y también un XML. Hasta ahora obtuve este código:

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

No sé exactamente por dónde empezar, por favor tenga paciencia.

EDIT:

Código completo de Bryant Luk (gracias!)

@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

Intente comenzar explicando cuál es su problema. Hasta ahora, solo ha descrito lo que ha hecho, pero no ha mencionado lo que sucede cuando se ejecuta el código, los errores que ha encontrado, etc. –

+0

¿Está tratando de hacer que el marco llame a su 'getFile() 'para cada solicitud en'/download', para que pueda generar el archivo solicitado? Creo * que lo que estás preguntando, en ese caso, es cómo la implementación de 'getFile()' puede descubrir lo que realmente se solicitó. – Wyzard

+0

@Wyzard sí, espero que no sea mucho pedir tipo de implementación y anotación –

Respuesta

15

Si va a devolver cualquier archivo, es posible que desee hacer su método más "genérico" y devolver una javax.ws .rs.core.Response que se puede establecer la cabecera Content-Type programación:

@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

también usamos CXF y primavera, y este es mi API preferible.

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); 
    } 
} 
Cuestiones relacionadas